计算两个日期的天数问题
2016-10-12 17:39
351 查看
工程中,我们偶尔需要用到计算两个日期之间的年、月、日数分别是多少。这时候有个简单的方法而不是时间戳去转化计算显得格外重要。
话不多说,上代码:
两种方法都是利用 NSDateComponents 这一类型来获取具体的天数的。
话不多说,上代码:
1 // 获取某一时间(默认为当前时间)若干年、月、日之后的时间NSDate 2 + (NSDate *)dateWithFromDate:(NSDate * _Nullable)date years:(NSInteger)years months:(NSInteger)months days:(NSInteger)days{ 3 4 NSDate * latterDate; 5 6 // 判断是否传进来了日期NSDate:若有,则使用;若没有,则使用当前日期 7 if (date) { 8 9 latterDate = date; 10 }else{ 11 12 latterDate = [NSDate date]; 13 } 14 15 // 初始化 日历 16 NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 17 18 // 初始化 时间成分;它的各个属性就是 年月日时分秒 19 NSDateComponents *comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:latterDate]; 20 21 [comps setYear:years]; 22 [comps setMonth:months]; 23 [comps setDay:days]; 24 25 return [calendar dateByAddingComponents:comps toDate:latterDate options:0]; 26 }
1 @objc private func prepareDays(date: NSDate) -> NSInteger { 2 3 let calendar: NSCalendar = NSCalendar.init(calendarIdentifier: NSCalendarIdentifierGregorian)! 4 5 let comp: NSDateComponents = calendar.components(NSCalendarUnit.Day, fromDate: date, toDate: NSDate(), options: NSCalendarOptions.WrapComponents) 6 7 return comp.day 8 }
两种方法都是利用 NSDateComponents 这一类型来获取具体的天数的。
相关文章推荐
- 计算任意两个日期之间的天数问题
- iOS 计算两个日期之间的天数问题
- 计算两个日期相差的天数
- 计算两个日期的间隔天数
- 计算两个日期的天数差
- Java中计算任意两个日期之间的工作天数
- 怎样用javaScript计算两个日期字符串相差的天数?
- C#中计算两个日期间隔的天数
- JAVA计算两个日期之间的天数
- SQL计算两个日期之间的工作天数
- Java中计算任意两个日期之间的工作天数
- 计算两个日期之间的工作天数
- 如何计算两个日期之间相隔的天数?calendar的用法
- asp.net中计算两个日期之间的相差的天数的方法(vb)
- JS 计算两个日期相差天数
- javascript计算两个日期的间隔天数
- asp.net中计算两个日期之间的相差的天数的方法(vb)
- 计算两个日期之间的间隔天数、周末天数、以及为当年的哪一周
- PHP中怎样计算两个日期相差的天数
- JS计算两个日期之间的天数