Godfather Godfather - 2 months ago 7
iOS Question

Parse a string date into date

let date = "2016-05-31T19:00:00+02:00"

let dateFormatterWithTime: DateFormatter {
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss Z"
return df
}
let thisIsNil = dateFormatterWithTime.date(from: date)


What is wrong with the formatter? According to http://nsdateformatter.com/ it returns a valid date, but I'm getting nil from this

Answer

Your formatter should be "yyyy-MM-dd'T'HH:mm:ssZ". Mark that the Z, that is meant for Zone have no gap in between second and Zone in your date but in your format there is a Gap

Hence the code should be

    let date = "2016-05-31T19:00:00+02:00"

    var dateFormatterWithTime: DateFormatter {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        return df
    }
    let thisIsNil = dateFormatterWithTime.date(from: date)

    print("date \(thisIsNil)")

Output Log:

date Optional(2016-05-31 17:00:00 +0000)
Comments