Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mdhansen5

macrumors member
Original poster
Nov 22, 2010
43
0
Colorado
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.
Code:
    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!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.