NSDateFormatter返回意外结果

时间:2011-01-04 21:24:34

标签: iphone ios nsdate nsdateformatter

为什么以下iOS 4.2代码会返回两个不同的时间?

  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);

返回:

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

第一个值是预期的,但我希望第二个值是相同的。

布鲁斯

2 个答案:

答案 0 :(得分:8)

您的日期格式似乎都不包含时区,因此您可能会获得您的位置与GMT之间的差异。

答案 1 :(得分:2)

由于dateString已经是GMT,因此诀窍是在inputFormatter上将时区设置为GMT。此代码按预期工作:

  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);

返回:

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