ISO8601DateFormatter不将字符串转换为日期

我有这个日期时间字符串 2020-03-09T11:53:39.474Z 。我需要将其转换为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")
}

但是它无法正确转换。

知道为什么会这样吗?

agercaigao 回答:ISO8601DateFormatter不将字符串转换为日期

init()中的designated initialiser ISO8601DateFormatter执行此操作:

默认情况下,格式化程序会初始化为使用GMT时区,RFC 3339标准格式(“ yyyy-MM-dd'T'HH:mm:ssZZZZZZZ”)和以下选项:withInternetDateTimewithDashSeparatorInDatewithColonSeparatorInTimewithTimeZone

很显然,您的日期不是采用yyyy-MM-dd'T'HH:mm:ssZZZZZ格式,因为它具有毫秒部分。

您只需要添加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")
}

我个人想列出所有选项以使代码更清晰,但您也可以这样做:

formatter.formatOptions.insert(.withFractionalSeconds)
本文链接:https://www.f2er.com/2673248.html

大家都在问