计算日期间隔方式比较常见的方式如下:
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setFirstWeekday:2];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *fromDate = [dateFormatter dateFromString:@"2014-06-23 12:02:03"];
NSDate *toDate = [NSDate date];
NSDateComponents *dayComponents = [gregorian components:NSDayCalendarUnitfromDate:fromDate toDate:toDate options:0];
// dayComponents.day 即为间隔的天数
initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setFirstWeekday:2];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *fromDate = [dateFormatter dateFromString:@"2014-06-23 12:02:03"];
NSDate *toDate = [NSDate date];
NSDateComponents *dayComponents = [gregorian components:NSDayCalendarUnitfromDate:fromDate toDate:toDate options:0];
// dayComponents.day 即为间隔的天数
这个大多数情况下似乎是正确的,但是在某些时刻会发下它的结果又是错误的。实际上它计算出的天间隔还是依赖于两个日期间的小时数来判断是否满足一天的间隔。例如:两个日期2014-06-23 13:00:00 和 2014-06-24 10:00:00,在这个方法下计算会得出两个日期的间隔并没有到一天,因为他们的小时数间隔并没有达到24个小时。但我们想让它们的间隔为一天,那么就需要对两个日期进行处理,做法是,把两个日期的钟点抹平——即设置为00:00:00,代码如下:
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setFirstWeekday:2];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *fromDate;
NSDate *toDate;
[gregorian rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:[dateFormatter dateFromString:@"2014-06-23 12:02:03"]];
[gregorian rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:[NSDate date]];
NSDateComponents *dayComponents = [gregorian components:NSDayCalendarUnitfromDate:fromDate toDate:toDate options:0];
// dayComponents.day 即为间隔的天数
initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setFirstWeekday:2];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *fromDate;
NSDate *toDate;
[gregorian rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:[dateFormatter dateFromString:@"2014-06-23 12:02:03"]];
[gregorian rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:[NSDate date]];
NSDateComponents *dayComponents = [gregorian components:NSDayCalendarUnitfromDate:fromDate toDate:toDate options:0];
// dayComponents.day 即为间隔的天数