0

NSDateFormatter用来将日期NSString实例转换为NSDate对象。有一次,我意识到有些地方不对劲,当我进行检查NSDateFormatter时,从字符串转换为NSDate.

代码如下所示:

NSString *dateString = [dictionary objectForKey:@"match_date_time"];
if (dateString) {
     // dateString is "2012-10-30 04:30:00"

     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
     [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

     self.date = [formatter dateFromString:dateString];
     // self.date ends up 2011-10-30 04:30:00 +0000, yes 2011 not 2012.
}

有谁知道为什么NSDateFormatter失败如此悲惨?

谢谢!

4

1 回答 1

1

只需写下面的代码

[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
于 2012-10-20T11:24:33.540 回答