如何在NSDate中跳过时间?

Nuz*_*ari 5 objective-c nsdate

我希望跳日期之间的差异意味着如果一个日期是2012年1月13日 - 晚上11点,其他日期是2012年1月14日 - 上午12点,那么差异应该是1天而不是0天.我的意思是我想要仅在日期之间区别, 2012年1月14日 - 2012年1月13日,跳过时间.我知道我可以使用NSDate api来计算差异,但问题是它也考虑时间.所以我想在计算差异时我会跳过时间但我不知道如何跳过时间因为如果我使用NSDateFormatter它将返回字符串而不是日期.请帮帮我,我能做什么?

提前致谢!

Jos*_*erg 7

您需要做的是先获取NSDateComponents每个日期.一旦你这样做,你可以比较'天'组件,以让你与众不同.

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *date1 = ....;
NSDate *date2 = ....;
NSDateComponents *comps1 = [cal components:NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit fromDate:date1];
NSDateComponents *comps2 = [cal components:NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit fromDate:date2];

date1 = [cal dateFromComponents:comps1];
date2 = [cal dateFromComponents:comps2];

NSDateComponents *diffComps = [cal components:NSDayCalendarUnit fromDate:date1 toDate:date2 options:0];

NSLog(@"Days diff = %d", diffComps.day);
Run Code Online (Sandbox Code Playgroud)

日期API可能有点奇怪,但是一旦你做到这一点就非常强大.