Search code examples
iosswiftnsdateformatterdateformatter

Swift: Converting ISO8601 to Date


Trying to convert ISO8601 formatted String into Date and getting a nil.

let dateString = "2020-06-27T16:09:00+00:00" // ISO8601

I tried two different ways:

import Foundation
let df = DateFormatter()
df.timeZone = TimeZone.current
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let toDate = df.date(from: dateString)

print("toDate \(String(describing: toDate))") // output: toDate nil

I also tried:

import Foundation
let isoDateFormatter = ISO8601DateFormatter()
isoDateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
isoDateFormatter.formatOptions = [
    .withFullDate,
    .withFullTime,
    .withDashSeparatorInDate,
    .withFractionalSeconds]
let isoDate = isoDateFormatter.date(from: dateString)
print("isoDate \(isoDate)") // output: isoDate nil

Date format in String is ISO8601. I validated it here: http://jsfiddle.net/wq7tjec7/14/

Can't figure out what I am doing wrong.


Solution

  • As @Martin has mentioned in the comments your date doesn't have the fractional seconds at the end of the string. Here's the right format:

    df.dateFormat = "yyyy-MM-dd'T'HH:mm:SSxxxxx"
    

    or remove the withFractionalSeconds from formatOptions array of isoDateFormatter, like this:

    isoDateFormatter.formatOptions = [
        .withFullDate,
        .withFullTime,
        .withDashSeparatorInDate]
    

    Update: As @Leo has mentioned in the comments the use of Z for time zone's format is wrong here, it needs to be xxxxx instead.