我使用 NSDateFormatter
将日期 NSString
实例转换为 NSDate
对象。有一次,我意识到有些事情不对劲,当我检查时,从字符串转换为 NSDateFormatter 时似乎损失了一整年的时间。 .
代码如下所示:
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
失败得如此惨烈?
谢谢!
最佳答案
只需编写下面的代码
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
关于objective-c - NSDateFormatter 损失了一年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12987901/