简体   繁体   English

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

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

I'm pulling a date from a JSON database. 我正在从JSON数据库中提取日期。 The Date is formatted like 2017-06-16T13:38:34.601767 (ISO8601 I think). 日期格式为2017-06-16T13:38:34.601767(我认为是ISO8601)。 I'm trying to use the ISO8601DateFormatter to format the date from 2017-06-16T13:38:34.601767 to 2017-06-16. 我正在尝试使用ISO8601DateFormatter格式化2017-06-16T13:38:34.601767到2017-06-16的日期。 So far I can't even get the pulled string to format as a date. 到目前为止,我甚至无法将拉出的字符串格式化为日期。

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

I'm not sure if I've got the date format wrong and it's not ISO8601 or if I'm not using the ISO8601DateFormatter as intended. 我不确定我的日期格式是否错误,它不是ISO8601,或者我没有按照预期使用ISO8601DateFormatter。

1.) Is it an ISO8601 Date? 1.)是ISO8601日期?
2.) Am I using the ISO8601DateFormatter correctly? 2.)我是否正确使用ISO8601DateFormatter?

Thanks! 谢谢!

ISO8601 has several different options, including a timezone. ISO8601有几种不同的选择,包括时区。 It appears that by default the ISO8601DateFormatter expects a timezone indicator in the string. 看来默认情况下, ISO8601DateFormatter需要字符串中的时区指示符。 You can disable this behaviour by using custom options like so: 您可以使用自定义选项禁用此行为,如下所示:

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)

If you want to know what are the default options, just run this code in a playground: 如果您想知道默认选项是什么,只需在游乐场中运行此代码:

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)

Of course, if your string doesn't contain a timezone, the date formatter will still interpret it in a timezone using its timeZone property, which – according to the documentation – defaults to GMT. 当然,如果您的字符串不包含时区,则日期格式化程序仍将使用其timeZone属性在时区中对其进行timeZone ,根据文档,该属性默认为GMT。

Remember to change it before using the formatter if you want to interpret your date in a different timezone: 如果要在不同的时区解释日期,请记住在使用格式化程序之前更改它:

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

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

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