繁体   English   中英

将ISO8601字符串转换为重新格式化的日期字符串(Swift)

[英]convert ISO8601 String to reformatted date string(Swift)

我正在从JSON数据库中提取日期。 日期格式为2017-06-16T13:38:34.601767(我认为是ISO8601)。 我正在尝试使用ISO8601DateFormatter格式化2017-06-16T13:38:34.601767到2017-06-16的日期。 到目前为止,我甚至无法将拉出的字符串格式化为日期。

let pulledDate = self.pulledRequest.date
var dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from: pulledDate)
print(date!) //nil

我不确定我的日期格式是否错误,它不是ISO8601,或者我没有按照预期使用ISO8601DateFormatter。

1.)是ISO8601日期?
2.)我是否正确使用ISO8601DateFormatter?

谢谢!

ISO8601有几种不同的选择,包括时区。 看来默认情况下, ISO8601DateFormatter需要字符串中的时区指示符。 您可以使用自定义选项禁用此行为,如下所示:

let pulledDate = "2017-06-16T13:38:34.601767"
var dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withYear, .withMonth, .withDay, .withTime, .withDashSeparatorInDate, .withColonSeparatorInTime]
let date = dateFormatter.date(from: pulledDate)

如果您想知道默认选项是什么,只需在游乐场中运行此代码:

let dateFormatter = ISO8601DateFormatter()
let options = dateFormatter.formatOptions
options.contains(.withYear)
options.contains(.withMonth)
options.contains(.withWeekOfYear)
options.contains(.withDay)
options.contains(.withTime)
options.contains(.withTimeZone)
options.contains(.withSpaceBetweenDateAndTime)
options.contains(.withDashSeparatorInDate)
options.contains(.withColonSeparatorInTime)
options.contains(.withColonSeparatorInTimeZone)
options.contains(.withFullDate)
options.contains(.withFullTime)
options.contains(.withInternetDateTime)

当然,如果您的字符串不包含时区,则日期格式化程序仍将使用其timeZone属性在时区中对其进行timeZone ,根据文档,该属性默认为GMT。

如果要在不同的时区解释日期,请记住在使用格式化程序之前更改它:

dateFormatter.timeZone = TimeZone(identifier: "Europe/Paris")

暂无
暂无

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

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