将ISO8601字符串转换为重新格式化的日期字符串(Swift)
问题描述:
我从JSON数据库中提取日期。日期格式如2017-06-16T13:38:34.601767(ISO8601我认为)。我正在尝试使用ISO8601DateFormatter将日期从2017-06-16T13:38:34.601767设置为2017-06-16。到目前为止,我甚至无法将拉字符串格式化为日期。将ISO8601字符串转换为重新格式化的日期字符串(Swift)
let pulledDate = self.pulledRequest.date
var dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from: pulledDate)
print(date!) //nil
我不知道如果我有日期的格式错误,它如果我不使用ISO8601DateFormatter按预期不ISO8601或。
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
属性在时区中解释该属性,根据文档,该属性默认为GMT。
请记住,如果你想诠释你的约会对象在不同的时区使用格式化之前改变它:
dateFormatter.timeZone = TimeZone(identifier: "Europe/Paris")
你确定你有你的毫秒块(0.601767)6位数字? –
不幸的是,是的。那也一直在扔我。我看到有人在某处(我知道,这是有帮助的哈哈)说他们有同样的事情,它是ISO8601 – froggomad