这是代码摘录:
func mapping(map: Map) {
time <- (map["time"], TransformOf<Date, String>(fromJSON: {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
//dateFormatter.timeZone = TimeZone(abbreviation: "EEST")
if let argument = $0 {
let date = dateFormatter.date(from: argument)
return dateFormatter.date(from: argument)
}
return nil
}}
$0
是带有"22:12:00"
的字符串。我输入“ let date”以查看返回的内容,并且为零。我在这里查找格式代码:http://waracle.net/iphone-nsdateformatter-date-formatting-table/代码应该实际工作。我究竟做错了什么?
编辑:添加了整个功能
EDIT2:我刚刚注意到它在iPhone 7 iOS 10.1模拟器上可以正常工作,但在iPod 10.1.1(2016)上返回nil。太奇怪了
最佳答案
从Technical Q&A QA1480 – NSDateFormatter and Internet Dates(添加重点):
另一方面,如果您使用固定格式的日期,则应首先将日期格式器的语言环境设置为适合您的固定格式的语言环境。在大多数情况下,最佳选择的语言环境是“ en_US_POSIX”,该语言环境专门设计用于产生美式英语结果,而不考虑用户和系统偏好。
这将防止根据日期解释日期
用户的区域设置:
let dateFormatter = DateFormatter()
// Set the locale first ...
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
// ... and then the date format:
dateFormatter.dateFormat = "HH:mm:ss"
// ...
另请参见What is the best way to deal with the NSDateFormatter locale "feechur"?。
关于ios - DateFormatter不返回“HH:mm:ss”的日期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58772737/