简体   繁体   English

-[NSCalendar组件:fromDate:toDate:options]始终返回0 diff

[英]-[NSCalendar components:fromDate:toDate:options] always returns 0 diff

I have read some threads on how to calc diff between 2 dates in iOS, here is an example which also seems to be provided by Apple docs, and I use it to decide if 2 dates are the same (ignoring the time). 我已经阅读了一些有关如何计算iOS中2个日期之间的差异的线程,这是Apple文档似乎也提供的示例,我用它来确定2个日期是否相同(忽略时间)。 But the components: method always returns year=0, month=0, day=0, even if the 2 dates are different. 但是组件:方法始终返回year = 0,month = 0,day = 0,即使两个日期不同。 I have no idea why... I'd appreciate your thought... 我不知道为什么...我会很感激你的想法...

+ (BOOL)isSameDate:(NSDate*)d1 as:(NSDate*)d2 {
if (d1 == d2) return true;
if (d1 == nil || d2 == nil) return false;

NSCalendar* currCal = [NSCalendar currentCalendar];

// messing with the timezone - can also be removed, no effect whatsoever:
NSTimeZone* tz = [NSTimeZone timeZoneForSecondsFromGMT:0];
[currCal setTimeZone:tz];

NSDateComponents* diffDateComps =
[currCal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
        fromDate:d1 toDate:d2 options:0];

return ([diffDateComps year] == 0 && [diffDateComps month] == 0 && [diffDateComps day] == 0);
}

Ok I found the issue, it did not happen with every date, only with consecutive ones. 好的,我发现了这个问题,并不是每个日期都发生此问题,只有连续的日期才发生。 It turns out that 'isSameDate' is not implemented correctly as component:fromDate:toDate will return 0 for dec 23 8:00, dec 24 07:59 even if time components are not in the component flags! 事实证明,“ isSameDate”未正确实现为component:fromDate:toDate在12月23日8:00和12月24日07:59都将返回0,即使时间分量不在组件标志中! But it will return 1 for dec 23 8:00, dec 24 8:01. 但是它将在12月23日8:00、12月24日8:01返回1。

To fix my method, I needed to perform something else: 要修复我的方法,我需要执行其他操作:

NSDateComponents* c1 =
    [currCal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
        fromDate:d1];

NSDateComponents* c2 =
    [currCal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
        fromDate:d2];

return ([c1 day] == [c2 day] && [c1 month] == [c2 month] && [c1 year] == [c2 year]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM