ISO8601DateFormatter 未将字符串转换为日期
ISO8601DateFormatter not converting a string to date
我有这个日期时间字符串 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")
}
但是无法正确转换。
知道为什么会这样吗?
ISO8601DateFormatter
的 designated initialiser 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
.
显然,您的日期不是 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)
我有这个日期时间字符串 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")
}
但是无法正确转换。
知道为什么会这样吗?
ISO8601DateFormatter
的 designated initialiser 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
, andwithTimeZone
.
显然,您的日期不是 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)