简体   繁体   English

Swift:将 ISO8601 转换为日期

[英]Swift: Converting ISO8601 to Date

Trying to convert ISO8601 formatted String into Date and getting a nil .尝试将ISO8601格式的String转换为Date并获得nil

let dateString = "2020-06-27T16:09:00+00:00" // ISO8601

I tried two different ways:我尝试了两种不同的方法:

import Foundation
let df = DateFormatter()
df.timeZone = TimeZone.current
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let toDate = df.date(from: dateString)

print("toDate \(String(describing: toDate))") // output: toDate nil

I also tried:我也试过:

import Foundation
let isoDateFormatter = ISO8601DateFormatter()
isoDateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
isoDateFormatter.formatOptions = [
    .withFullDate,
    .withFullTime,
    .withDashSeparatorInDate,
    .withFractionalSeconds]
let isoDate = isoDateFormatter.date(from: dateString)
print("isoDate \(isoDate)") // output: isoDate nil

Date format in String is ISO8601 . String中的日期格式为ISO8601 I validated it here: http://jsfiddle.net/wq7tjec7/14/我在这里验证了它: http://jsfiddle.net/wq7tjec7/14/

Can't figure out what I am doing wrong.无法弄清楚我做错了什么。

As @Martin has mentioned in the comments your date doesn't have the fractional seconds at the end of the string.正如@Martin 在评论中提到的那样,您的日期在字符串末尾没有小数秒。 Here's the right format:这是正确的格式:

df.dateFormat = "yyyy-MM-dd'T'HH:mm:SSxxxxx"

or remove the withFractionalSeconds from formatOptions array of isoDateFormatter , like this:或从withFractionalSecondsformatOptions数组中删除isoDateFormatter ,如下所示:

isoDateFormatter.formatOptions = [
    .withFullDate,
    .withFullTime,
    .withDashSeparatorInDate]

Update: As @Leo has mentioned in the comments the use of Z for time zone's format is wrong here, it needs to be xxxxx instead.更新:正如@Leo 在评论中提到的,这里使用Z作为时区格式是错误的,它需要改为xxxxx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM