ios - DateFormatter 不返回 "HH:mm:ss"的日期

标签 ios swift date swift3

以下是代码摘录:

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/

相关文章:

iOS 嵌套 ScrollView ——继续滚动到顶部进入 super View ?

javascript - 如何使用 Objective-C 从 IOS Cordova 中的设备(本地数据库)中删除图像

ios - 使用 Swift 在 iOS 中平滑搜索栏动画

MySQL 查询显示下个月内的所有小时

php - 将工作时间添加到时间戳

ios - MKLocalSearch 没有找到明显的结果

ios - Swift 3 - MKPointAnnotation 自定义图像

swift - Vapor:处理 HTTPS 请求?

java - java中如何比较两个日期?

ios - didBeginContact 不触发