4

Why does the following iOS 4.2 code return two different times?

  NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
  NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
  [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  [dateFormatter setTimeZone:gmt];
  NSString* dateString = [dateFormatter stringFromDate:[NSDate date]];
  NSLog(@"Date/Time is %@", dateString);

  NSDateFormatter *inputFormatter = [[[NSDateFormatter alloc] init] autorelease];
  [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];    
  NSDate* date = [inputFormatter dateFromString:dateString];        
  NSLog(@"Date/Time is %@", date);

Returns:

2011-01-04 16:15:12.966 WA[687:207] Date/Time is 2011-01-04 21:15:12
2011-01-04 16:15:12.967 WA[687:207] Date/Time is 2011-01-05 02:15:12 +0000

The first value is expected, but I would expect the second to be the same.

Bruce

bvanderw
  • 1,065
  • 2
  • 12
  • 20
  • It looks like the formatter does not see a need to display the time zone if a time zone was set. – Joe Jan 04 '11 at 21:29

2 Answers2

8

Neither of your date formats appear to include the time zone, so you're likely getting the difference between your location and GMT.

Joshua Nozzi
  • 60,946
  • 14
  • 140
  • 135
  • I am setting the time zone on the first NSDateFormatter to GMT, and that value is the correct GMT time. – bvanderw Jan 04 '11 at 21:49
  • I think you are correct. It is applying the system time zone to the string passed into inputFormatter, then displaying the GMT offset from that. Since the dateString is already GMT, the trick is to set the time zone to GMT on that NSDateFormatter as well. – bvanderw Jan 04 '11 at 21:58
2

Since dateString is already GMT, the trick is to set the time zone to GMT on inputFormatter as well. This code works as expected:

  NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
  NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
  [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  [dateFormatter setTimeZone:gmt];
  NSString* dateString = [dateFormatter stringFromDate:[NSDate date]];
  NSLog(@"Date/Time is %@", dateString);

  NSDateFormatter *inputFormatter = [[[NSDateFormatter alloc] init] autorelease];
  [inputFormatter setTimeZone:gmt];
  [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];    
  NSDate* date = [inputFormatter dateFromString:dateString];        
  NSLog(@"Date/Time is %@", date);

returns:

2011-01-04 16:50:35.369 WA[888:207] Date/Time is 2011-01-04 21:50:35
2011-01-04 16:50:35.370 WA[888:207] Date/Time is 2011-01-04 21:50:35 +0000
bvanderw
  • 1,065
  • 2
  • 12
  • 20