Search code examples
iosiphoneswiftnsdateformatter

Formatting JSON date to Swift date doesn't work


I'm trying to format this date: 2018-01-10T11:57:21.153 to Swift Date object like this:

let dateSentString = jsonDict["date"] as! String
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from: dateSentString)!

For some reason, the app crashes on the last line.

What am I doing wrong? Thanks!


Solution

  • change the milli seconds format use 'SSS' specifier (with number of S's equal to number of digits of milliseconds ). for more information you get here

    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
    

    from

    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    

    Full code

       let dateSentString = "2018-01-10T11:57:21.153"
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
        let date = dateFormatter.date(from: dateSentString)!
        print(date)