0

I've been using NSCalendar and NSDateComponents to return the difference (in days) between 2 dates. Here's the code I'm using to get that.

NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

NSDate *todayDate = [NSDate date];
NSDateComponents *comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) 
                                 fromDate:todayDate];
[comps setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSDate *today = [calendar dateFromComponents:comps];

NSDate *startDate = self.date;
NSDate *endDate =  today;
NSLog(@"startDate: %@",startDate);
NSLog(@"endDate: %@",endDate);

NSDateComponents *components = [calendar components:NSDayCalendarUnit
                                            fromDate:endDate
                                              toDate:startDate
                                             options:0];
[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSInteger days = [components day];

The weird part is that this works perfectly during the early part of the day, but once I reach around 6 or 7PM (I'm using Mountain Time, which is GMT -7 I think), it stops working correctly. Instead of a returning the correct difference, it returns the difference minus 1 day. so For example, it returns -1 instead of 0, or 1 instead of 2.

I'm guessing this is a time zone issue. Does anyone know how to fix it? I've tried setting the timeZone for my NSCalendar and the NSDateComponents to GMT, local and system, but none seem to work.

Any ideas?

Thank you!

4

1 回答 1

0

It looks like the code is not handling the fractional difference between days. For example, if the start date is yesterday at 11:59 PM and the end date is today at 12:01 AM, the code will report the difference as 0 days. If you consider that to be a 1 day difference, then the code needs to handle that case.

If you are selecting self.date with a date picker, self.date contains the date plus the current local time. At 6 or 7 PM your local time, it's midnight GMT (i.e., tomorrow WRT your local time), which causes the unexpected -1 in your difference calculation.

于 2012-08-08T07:56:58.897 回答