Sagi Mann
Sagi Mann

Reputation: 3610

-[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). But the components: method always returns year=0, month=0, day=0, even if the 2 dates are different. 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);
}

Upvotes: 2

Views: 2369

Answers (1)

Sagi Mann
Sagi Mann

Reputation: 3610

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! But it will return 1 for dec 23 8:00, dec 24 8:01.

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]);

Upvotes: 1

Related Questions