1.用日历计算相差天数(默认会把时间也算上)如下:
//2017-03-20 15:58:50 [NSDate date]
//2017-03-24 01:13:59 startDate
NSDate *startTime = [NSDate dateWithTimeIntervalSince1970:1490289239];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = kCFCalendarUnitYear | kCFCalendarUnitMonth | NSCalendarUnitDay | kCFCalendarUnitHour | kCFCalendarUnitMinute | kCFCalendarUnitSecond;
NSDateComponents *dateComponents = [calendar components:unit fromDate:[NSDate date] toDate:startDate options:0];
NSLog(@"%@", dateComponents);
输出结果:
2017-03-20 15:58:48.722 111[14894:146007] <NSDateComponents: 0x60000014ed30> Calendar Year: 0 Month: 0 Day: 3 Hour: 9 Minute: 15 Second: 10
为这个时候你就会发现,20跟24号,我们实际想要的结果是4天,但是这个得到的结果却是3天。解决方法如下:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = kCFCalendarUnitYear | kCFCalendarUnitMonth | NSCalendarUnitDay | kCFCalendarUnitHour | kCFCalendarUnitMinute | kCFCalendarUnitSecond;
NSDateComponents *currentDateCompontes = [calendar components:unit fromDate:[NSDate date]];
NSDateComponents *startDateCompontes = [calendar components:unit fromDate:startTime];
NSDate *currentDate = [calendar dateFromComponents:[self transformDate:currentDateCompontes]];
NSDate *startDate = [calendar dateFromComponents:[self transformDate:startDateCompontes]];
NSDateComponents *dateComponents = [calendar components:unit fromDate:currentDate toDate:startDate options:0];
NSLog(@"%@", dateComponents);
//将时分秒设置为00:00:00 只计算日期相差天数
- (NSDateComponents *)transformDate:(NSDateComponents *)currentDate;
{
NSDateComponents *dateCompontes = [[NSDateComponents alloc] init];
[dateCompontes setYear:currentDate.year];
[dateCompontes setMonth:currentDate.month];
[dateCompontes setDay:currentDate.day];
[dateCompontes setHour:0];
[dateCompontes setMinute:0];
[dateCompontes setSecond:0];
return dateCompontes;
}
2017-03-20 16:06:26.768 111[15157:150705] <NSDateComponents: 0x608000143de0> Calendar Year: 0 Month: 0 Day: 4 Hour: 0 Minute: 0 Second: 0
这样就和预想的结果一样了。
2.还有一种方法就是拿到日期,直接对天进行相减操作也可实现
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = kCFCalendarUnitYear | kCFCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents *currentDateCompontes = [calendar components:unit fromDate:[NSDate date]];
NSDateComponents *startDateCompontes = [calendar components:unit fromDate:startTime];
NSLog(@"%ld", startDateCompontes.day - currentDateCompontes.day);
2017-03-20 16:14:31.910 111[15433:155187] 4