开发者

NSDateFormatter returns unexpected results

开发者 https://www.devze.com 2023-02-03 01:29 出处:网络
Why does the following iOS 4.2 code return two different times? NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@\"GMT\"];

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 st开发者_开发知识库ringFromDate:[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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号