Here is the code excerpt:
下面是代码摘录:
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 =
Here is the code excerpt:
下面是代码摘录:
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 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: https://waracle.net/iphone-nsdateformatter-date-formatting-table/
$0是“22:12:00”的字符串。我输入“let date”来查看它的返回值,它是nil。我查阅了这里的格式代码:https://waracle.net/iphone-nsdateformatter-date-formatting-table/。
Code should work actually. What am I doing wrong?
代码应该工作。我做错了什么?
EDIT: Added the whole function
编辑:添加整个功能
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.
我刚刚注意到它在iPhone 7 iOS 10.1模拟器上运行正常,但在我的iPod 10.1.1(2016)上返回nil。这是如此的奇怪。
1 个解决方案
#1
18
From Technical Q&A QA1480 – NSDateFormatter and Internet Dates:
从技术问答QA1480 - NSDateFormatter和Internet日期:
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.
另一方面,如果使用固定格式的日期,您应该首先将日期格式化程序的语言环境设置为适合您的固定格式。在大多数情况下,最好选择的语言环境是“en_US_POSIX”,这是一种专门设计的语言环境,无论用户和系统的首选项是什么,都可以生成美式英语的结果。
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"
// ...
See also What is the best way to deal with the NSDateFormatter locale "feechur"?.
还可以看到处理NSDateFormatter语言环境“feedchur”的最佳方法是什么?
{
let date = dateFormatter.date(from: argument)
return dateFormatter.date(from: argument)
}
return nil
}}
func map