Dateformatter返回错误的年份2017-12-31

时间:2017-12-31 11:12:43

标签: ios nsdate

看看这段代码:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"YYYY-MM-dd";
formatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
NSString *dateString = [formatter stringFromDate:date];

日志:

Printing description of date:
2017-12-31 11:04:07 +0000
Printing description of dateString:
2018-12-31

我是如何得到 2018 ???

顺便说一句,这段代码适用于其他所有日期。它在2017-12-31只表现得很奇怪......

更新:

尝试使用系统时区,如评论中所示:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"YYYY-MM-dd";
formatter.timeZone = [NSTimeZone systemTimeZone];
NSString *dateString = [formatter stringFromDate:date];

日志:

Printing description of date:
2017-12-31 11:27:04 +0000
Printing description of dateString:
2018-12-31

0 个答案:

没有答案