以下是代码摘录:
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 (强调):
On the other hand, if you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences.
这将防止日期被解释为 用户的区域设置:
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/45160105/