[英]ISO8601DateFormatter not converting a string to date
I have this datetime string 2020-03-09T11:53:39.474Z .我有这个日期时间字符串2020-03-09T11:53:39.474Z 。 I need to convert it to a
Date
我需要将其转换为
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")
}
But it fails to convert it properly.但它无法正确转换它。
Any idea why this it's happening?知道为什么会这样吗?
The designated initialiser init()
of ISO8601DateFormatter
does this: ISO8601DateFormatter
的指定初始值设定项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
.默认情况下,格式化程序被初始化为使用 GMT 时区、RFC 3339 标准格式(“yyyy-MM-dd'T'HH:mm:ssZZZZZ”)和以下选项:
withInternetDateTime
、withDashSeparatorInDate
、withColonSeparatorInTime
和withTimeZone
.
Obviously, your date is not in the format yyyy-MM-dd'T'HH:mm:ssZZZZZ
, because it has a milliseconds component.显然,您的日期不是
yyyy-MM-dd'T'HH:mm:ssZZZZZ
,因为它具有毫秒分量。
You just need to add the withFractionalSeconds
option:您只需要添加
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")
}
I personally like to list the options all out to make the code clearer, but you can also do:我个人喜欢列出所有选项以使代码更清晰,但您也可以这样做:
formatter.formatOptions.insert(.withFractionalSeconds)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.