Search code examples
node.jsswiftisodatedateformatter

Node.js .toISOString() to Swift DateFormatter()


I'm getting the date and time from a server using .toISOString() which returns 2018-09-30T10:36:39.165Z.

I then want to convert this to a Date() in Swift so that I can manipulate it by adding an hour. I found a website saying the format for .toISOString() is YYYY-MM-DDTHH:mm:ss.sssZ.

I then set the format of the swift DateFormatter():

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DDTHH:mm:ss.sssZ"

However this does not seem to work as when I try to perform the conversion it fails:

guard let date = dateFormatter.date(from: time) else {
    fatalError("ERROR: Date conversion failed due to mismatched format.")
}

I assume it's an issue with the format string I'm using but I can't find what it should be, any ideas?


Solution

  • Put the T between 's:

    let time = "2018-09-30T10:36:39.165Z"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    
    let date = dateFormatter.date(from: time)