iOS - NSCalendar/NSDateComponents time zone issue?

Discussion in 'iOS Programming' started by mdhansen5, Jul 20, 2012.

  1. mdhansen5 macrumors member

    Joined:
    Nov 22, 2010
    Location:
    Colorado
    #1
    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!
     
  2. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #2

Share This Page