Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 277
Lyndon King McKay Avatar asked Jan 13 '17 06:01

Lyndon King McKay


People also ask

How do you string convert in to date in Swift?

Show activity on this post. let isoDate = "2016-04-14T10:44:00+0000" let dateFormatter = DateFormatter() dateFormatter. locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX dateFormatter. dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" let date = dateFormatter.

What is 000z in timestamp?

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC). What Z means in date? zero. What is a timestamp example? TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

What is the date format in Swift?

The date format of the string that is passed to date(from:) method is MM/dd/yy while the dateFormat property has a value of dd/MM/yy .


1 Answers

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)")
like image 150
Nirav D Avatar answered Sep 19 '22 13:09

Nirav D