[英]ISO8601DateFormatter returning nil for converting from valid string to date
我有一個 ISO8601 字符串,我想將它轉換為日期 object,但即使它是一個有效字符串,我仍然得到一個 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
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.