Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter returns unexpected results

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

like image 234
bvanderw Avatar asked Dec 28 '22 03:12

bvanderw


2 Answers

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

like image 72
Joshua Nozzi Avatar answered Jan 12 '23 12:01

Joshua Nozzi


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
like image 39
bvanderw Avatar answered Jan 12 '23 11:01

bvanderw