简体   繁体   English

ISO8601DateFormatter 不将字符串转换为日期

[英]ISO8601DateFormatter not converting a string to date

I have this datetime string 2020-03-09T11:53:39.474Z .我有这个日期时间字符串2020-03-09T11:53:39.474Z I need to convert it to a Date我需要将其转换为Date

let dateString = "2020-03-09T11:53:39.474Z"
if let date = ISO8601DateFormatter().date(from: dateString) {
    print(dateFormatter.string(from: date))
} else {
    print("Could not convert date")
}

But it fails to convert it properly.但它无法正确转换它。

Any idea why this it's happening?知道为什么会这样吗?

The designated initialiser init() of ISO8601DateFormatter does this: ISO8601DateFormatter指定初始值设定项init()执行以下操作:

By default, a formatter is initialized to use the GMT time zone, the RFC 3339 standard format ("yyyy-MM-dd'T'HH:mm:ssZZZZZ"), and the following options: withInternetDateTime , withDashSeparatorInDate , withColonSeparatorInTime , and withTimeZone .默认情况下,格式化程序被初始化为使用 GMT 时区、RFC 3339 标准格式(“yyyy-MM-dd'T'HH:mm:ssZZZZZ”)和以下选项: withInternetDateTimewithDashSeparatorInDatewithColonSeparatorInTimewithTimeZone .

Obviously, your date is not in the format yyyy-MM-dd'T'HH:mm:ssZZZZZ , because it has a milliseconds component.显然,您的日期不是yyyy-MM-dd'T'HH:mm:ssZZZZZ ,因为它具有毫秒分量。

You just need to add the withFractionalSeconds option:您只需要添加withFractionalSeconds选项:

let dateString = "2020-03-09T11:53:39.474Z"
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [
    .withInternetDateTime, 
    .withFractionalSeconds, 
    .withColonSeparatorInTime, 
    .withDashSeparatorInDate, 
    .withTimeZone]
if let date = formatter.date(from: dateString) {
    print(date)
} else {
    print("Could not convert date")
}

I personally like to list the options all out to make the code clearer, but you can also do:我个人喜欢列出所有选项以使代码更清晰,但您也可以这样做:

formatter.formatOptions.insert(.withFractionalSeconds)

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

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