Ad

Formatting JSON Date To Swift Date Doesn't Work

- 1 answer

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!

Ad

Answer

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)
Ad
source: stackoverflow.com
Ad