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"
的字符串.我把让日期"看看它返回什么,它是零.我在这里查找了格式代码:http://waracle.net/iphone-nsdateformatter-date-formatting-table/
$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?
EDIT:添加了整个功能
EDIT2:我刚刚注意到它在 iPhone 7 iOS 10.1 模拟器上运行正常,但在我的 iPod 10.1.1 (2016) 上返回 nil.这太奇怪了.
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 ...
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
// ... and then the date format:
dateFormatter.dateFormat = "HH:mm:ss"
// ...
另见 什么是处理 NSDateFormatter 语言环境feechur"的最佳方法?.
这篇关于DateFormatter 不返回“HH:mm:ss"的日期;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!