我有一个ISO8601字符串,我想将其转换为Date对象,但我一直得到一个nil,即使它是一个有效的字符串。这是我的代码:
let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [
.withFractionalSeconds,
.withInternetDateTime,
.withFractionalSeconds,
.withColonSeparatorInTime,
.withDashSeparatorInDate
]
let date = isoFormatter.date(from: self)
我的字符串是2020-04-10T21:13:40.880000
,2020-04-10T21:13:40
(无毫秒(也会发生同样的情况
.withInternetDateTime
是withFullDate
、withFullTime
、withDashSeparatorInDate
、withColonSeparatorInTime
和withColonSeparatorInTimeZone
的组合。该选项在字符串中需要一个时区,并且适用于"2020-04-10T21:13:40.880000Z"
,请注意后面的Z
。
选项withDashSeparatorInDate
、withColonSeparatorInTime
在代码中是多余的(除了重复的withFractionalSeconds
(。
要省略时区,必须将withInternetDateTime
替换为withFullDate
和withTime
let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [
.withFractionalSeconds,
.withFullDate,
.withTime, // without time zone
.withColonSeparatorInTime,
.withDashSeparatorInDate
]