您的位置:首页 > 其它

计算两个日期的天数问题

2016-10-12 17:39 351 查看
  工程中,我们偶尔需要用到计算两个日期之间的年、月、日数分别是多少。这时候有个简单的方法而不是时间戳去转化计算显得格外重要。

  话不多说,上代码:

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 这一类型来获取具体的天数的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: