Phrixus
Phrixus

Reputation: 1219

Swift unable to parse string date to Date object

I have the following date format:

2016-08-26T05:16:50.200Z

And I am trying to parse similar date formatted strings into Date objects in Swift 3.0.

Here is my effort:

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-mm-dd EEEEE HH:mm:ss Z"
formatter.locale = Locale(identifier: "us")

var date = formatter.date(from: date_str)!

Where date_str is of the format mentioned above. Unfortunately, swift don't recognize the format and returns nil.

Note: I don't want to change the string to match the formatter, but to adapt the formatter to the format of the string. String is of external source so I don't have the ability to change the string's format, but to stick with it and create a formatter that will recognize the string's date pattern.

Any ideas on where my format is wrong?

Upvotes: 1

Views: 902

Answers (1)

Nirav D
Nirav D

Reputation: 72410

You are making mistake here, Here T is not for Week detail, The T is just a marker for where the time part begins.

A single point in time can be represented by concatenating a complete date expression, the letter T as a delimiter, and a valid time expression. For example "2016-10-05T14:30".

So now just change your dateFomat to yyyy-MM-dd'T'HH:mm:ss.SSSZ and you will get correct date you want.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formatter.locale = Locale(identifier: "us")
var date = formatter.date(from: date_str)!
print(date)

Output:

enter image description here

Upvotes: 3

Related Questions