How to convert "2017-01-09T11:00:00.000Z" into Date in Swift 3?

Lyndon King McKay picture Lyndon King McKay · Jan 13, 2017 · Viewed 25.8k times · Source

My problem is that the date is nil.

My code looks like

print(article_date) // output "2017-01-09T11:00:00.000Z" as string
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let date : Date? = dateFormatter.date(from: article_date!)
print("date: \(date)")

I've tried a few formatters like "yyyy-MM-dd'T'HH:mm:ssZ", but nothing worked.

Answer

Nirav D picture Nirav D · Jan 13, 2017

You need to set both .SSS and Z with your dateFormat, so your dateFormat should be yyyy-MM-dd'T'HH:mm:ss.SSSZ.

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: "2017-01-09T11:00:00.000Z")
print("date: \(date)")