繁体   English   中英

Swift:将 ISO8601 转换为日期

[英]Swift: Converting ISO8601 to Date

尝试将ISO8601格式的String转换为Date并获得nil

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

我尝试了两种不同的方法:

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

我也试过:

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

String中的日期格式为ISO8601 我在这里验证了它: http://jsfiddle.net/wq7tjec7/14/

无法弄清楚我做错了什么。

正如@Martin 在评论中提到的那样,您的日期在字符串末尾没有小数秒。 这是正确的格式:

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

或从withFractionalSecondsformatOptions数组中删除isoDateFormatter ,如下所示:

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

更新:正如@Leo 在评论中提到的,这里使用Z作为时区格式是错误的,它需要改为xxxxx

暂无
暂无

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

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