ISO8601DateFormatter返回nil,用于从有效字符串转换为日期



我有一个ISO8601字符串,我想将其转换为Date对象,但我一直得到一个nil,即使它是一个有效的字符串。这是我的代码:

let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [
.withFractionalSeconds,
.withInternetDateTime,
.withFractionalSeconds,
.withColonSeparatorInTime,
.withDashSeparatorInDate
]
let date = isoFormatter.date(from: self)

我的字符串是2020-04-10T21:13:40.8800002020-04-10T21:13:40(无毫秒(也会发生同样的情况

.withInternetDateTimewithFullDatewithFullTimewithDashSeparatorInDatewithColonSeparatorInTimewithColonSeparatorInTimeZone的组合。该选项在字符串中需要一个时区,并且适用于"2020-04-10T21:13:40.880000Z",请注意后面的Z

选项withDashSeparatorInDatewithColonSeparatorInTime在代码中是多余的(除了重复的withFractionalSeconds(。


要省略时区,必须将withInternetDateTime替换为withFullDatewithTime

let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [
.withFractionalSeconds,
.withFullDate,
.withTime, // without time zone
.withColonSeparatorInTime,
.withDashSeparatorInDate
]

最新更新