简体   繁体   English

在Swift中解析ISO8601字符串到目前为止

[英]Parsing a ISO8601 String to Date in Swift

I am getting the next string from an API which claims 我从声称的API获取下一个字符串

All date formats are ISO8601. 所有日期格式均为ISO8601。

I am trying with the next code: 我正在尝试下一个代码:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let updatedAtStr = "2016-06-05T16:56:57.019+01:00"
let updatedAt = dateFormatter.date(from: updatedAtStr)

Unfortunately resulting updatedAt is nil 不幸的是造成updatedAt为零

Your date format is incorrect, you need to take into account the milliseconds. 您的日期格式不正确,您需要考虑毫秒。

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"

let updatedAtStr = "2016-06-05T16:56:57.019+01:00"
let updatedAt = dateFormatter.date(from: updatedAtStr) // "Jun 5, 2016, 4:56 PM"

Just to clarify, the addition of .SSS in the date format is what fixes the problem. 只是为了澄清,在日期格式中添加.SSS可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM