I’m converting date strings from a JSON file to Date format and most the time it works, but this example fails and I can’t figure out why. Any ideas appreciated! Thank you.
let input = "2015-06-20T00:47:00.484Z"
let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.sssZ"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
print("ConvertedOutput: (dateFormatter.date(from: input))")
2
Answers
For milliseconds, you should use
SSS
instead ofsss
like this –Your input is a date string which corresponds to ISO8601 standard. For such date strings, the Foundation has a ISO8601DateFormatter class which helps you avoid many edge cases which can lead to wrong date parsing and that’s why it’s suggested by Apple to use for such date strings this dedicated class than using DateFormatter.
Code with ISO8601DateFormatter
Code with DateFormatter
If you can’t use ISO8601DateFormatter then
you have to correct the date format which has wrong mask for fractional seconds: .SSS instead .sss
Both formatters returns: