OGeek|极客世界-中国程序员成长平台

标题: ios - NSDateFormatter dateFromString 1981-04-01 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:03
标题: ios - NSDateFormatter dateFromString 1981-04-01

我有代码:

NSString *str = @"1981-04-01";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat"yyyy-MM-dd"];
NSDate *back = [dateFormatter dateFromString:str];

NSLog("output: %@", back); //output (null)

当我尝试不同的日期时:

str = @"1982-04-01";//也返回nil

str = @"1985-04-01";//看起来不错,输出:1985-03-31 20:00:00 +0000

看起来我的时区是 GMT+4。 在模拟器中测试:xcode 6.3、ios 8.3 (iphone5s)

为什么 NSDateFormatter 有时返回 nil?

我相信这与我所在的地区有关:爱沙尼亚。 有关 OSX 和 iOS 区域设置的图片。


(来源:ignis.ee)


(来源:ignis.ee)

已解决: 必须是夏令时开关问题。请阅读@Matthias Bauch 后面的评论。

  1. 添加 dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation"GMT"];效果很好!



Best Answer-推荐答案


我建议您将时区设置为像 GMT 一样

dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation"GMT"];

您认为的完整代码。 .

NSString *str = @"1981-04-01";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation"GMT"];
[dateFormatter setDateFormat"yyyy-MM-dd"];
NSDate *back = [dateFormatter dateFromString:str];

NSLog(@"output: %@", back);

你的输出像

output: 1981-04-01 00:00:00 +0000

关于ios - NSDateFormatter dateFromString 1981-04-01,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29621570/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4