[英]NSDateFormatter's dateFromString: returns nil in iOS 11
I've this code: 我有以下代码:
NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateStyle = NSDateFormatterLongStyle;
dateFormatter.timeStyle = NSDateFormatterLongStyle;
NSDate *myDate = [dateFormatter dateFromString:@"2016-03-01 13:42:17"];
For < iOS 11 , expected date is found, but for iOS 11 (Tested in iPhone with iOS 11.1) this is returning nil
. 对于<iOS 11 ,找到了预期的日期,但是对于iOS 11 (在装有iOS 11.1的iPhone中测试),返回nil
。
I didn't see any API changes for dateFromString: in Apple's doc. 我没有在Apple的文档中看到对dateFromString:的任何API更改。 What's wrong? 怎么了?
Basically do not use the date / time styles to convert a date string. 基本上不使用日期/时间样式来转换日期字符串。 The styles represent different strings in different locales. 样式在不同的语言环境中表示不同的字符串。
Use a fixed date format instead and set the locale to en_US_POSIX
: 请改用固定日期格式,并将语言环境设置为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's answer worked for me in Swift as well! @Vadian的答案在Swift中也对我有用! Thanks! 谢谢! :) :)
Here's the Swift version: 这是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.