DateFormatter不返回“HH:mm:ss”的日期。 [英] DateFormatter doesn't return date for "HH:mm:ss"
问题描述
这是代码摘录:
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-日期格式化表/
$0
is string with "22:12:00"
. I put "let date" to see what it returns and it's nil. I've looked up for format codes here: http://waracle.net/iphone-nsdateformatter-date-formatting-table/
代码应该正常工作,我做错了什么?
Code should work actually. What am I doing wrong?
ED IT :添加了整个功能
EDIT2 :我刚刚注意到它在iPhone 7 iOS 10.1模拟器上正常工作,但返回nil我的iPod 10.1.1(2016)。这很奇怪。
EDIT2: I just noticed it's working properly on iPhone 7 iOS 10.1 simulator but returns nil on my iPod 10.1.1 (2016). This is so weird.
推荐答案
从技术问答QA1480 - NSDateFormatter和Internet日期:
另一方面,如果您使用固定格式的日期,则应首先将日期格式化程序的区域设置设置为适合固定格式的内容。在大多数情况下,最适合选择的区域是en_US_POSIX,这是一个专门用于产生美国英语结果的区域设置,无论用户和系统偏好如何。
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.
这将阻止根据用户区域设置的
解释日期:
This will prevent the date from being interpreted according to the user's regional settings:
let dateFormatter = DateFormatter()
// Set the locale first ...
formatter.locale = Locale(identifier: "en_US_POSIX")
// ... and then the date format:
dateFormatter.dateFormat = "HH:mm:ss"
// ...
另请参见什么是处理NSDateFormatter区域设置功能的最佳方式?。
这篇关于DateFormatter不返回“HH:mm:ss”的日期。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!