繁体   English   中英

NSDateFormatter的dateFromString:在iOS 11中返回nil

[英]NSDateFormatter's dateFromString: returns nil in iOS 11

我有以下代码:

NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateStyle = NSDateFormatterLongStyle;
dateFormatter.timeStyle = NSDateFormatterLongStyle;

NSDate *myDate = [dateFormatter dateFromString:@"2016-03-01 13:42:17"];

对于<iOS 11 ,找到了预期的日期,但是对于iOS 11 (在装有iOS 11.1的iPhone中测试),返回nil

我没有在Apple的文档中看到对dateFromString:的任何API更改。 怎么了?

基本上不使用日期/时间样式来转换日期字符串。 样式在不同的语言环境中表示不同的字符串。

请改用固定日期格式,并将语言环境设置为en_US_POSIX

NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

NSDate *myDate = [dateFormatter dateFromString:@"2016-03-01 13:42:17"];

@Vadian的答案在Swift中也对我有用! 谢谢! :)

这是Swift版本:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

Date myDate = dateFormatter.date(from: "2016-03-01 13:42:17")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM