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 

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

布鲁斯

您的date格式都不包含时区,所以您可能会在您的位置和GMT之间获得差异。

由于dateString已经是格林尼治标准时间了,诀窍就是在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