NSDateFormatter腐败

时间:2013-07-17 05:36:39

标签: nsstring timezone nsdate nsdateformatter date-format

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSTimeZone *gmt = [NSTimeZone systemTimeZone];
[dateFormatter setTimeZone:gmt];

NSString* fileTime = [infoArray objectAtIndex:5];
NSDate* sessionStartDate = [dateFormatter dateFromString:fileTime];
NSLog(@"%@", [infoArray objectAtIndex:5]);
NSLog(@"%@", sessionStartDate);

两个NSLog:

2013-07-17 01:28:50
2013-07-17 05:28:50 +0000

两个应该是相同的,但不是。小时显示不同。我确实尝试'hh'而不是大写,但同样的问题。

1 个答案:

答案 0 :(得分:1)

您的系统时区不是GMT,而NSDateFormatter会解析日期字符串w.r.t GMT(您在日期字符串中缺少时区,因此它假定时区为GMT)。

所以你得到的是从时间字符串转换为你当地时间的GMT时间。

使用

  NSTimeZone *gmt = [NSTimeZone timeZoneWithName:@"GMT"];

你会得到相同的日期。