简体   繁体   中英

convert ISO8601 String to reformatted date string(Swift)

I'm pulling a date from a JSON database. The Date is formatted like 2017-06-16T13:38:34.601767 (ISO8601 I think). I'm trying to use the ISO8601DateFormatter to format the date from 2017-06-16T13:38:34.601767 to 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.

1.) Is it an ISO8601 Date?
2.) Am I using the ISO8601DateFormatter correctly?

Thanks!

ISO8601 has several different options, including a timezone. It appears that by default the ISO8601DateFormatter expects a timezone indicator in the string. 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.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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