1

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?

4
  • Maybe stupid question but have you tried to remove spaces so the string exactly matches format? "yyyy-mm-dd EEEEE HH:mm:ss Z" -> "yyyy-mm-ddEEEEEHH:mm:ssZ" Commented Oct 5, 2016 at 8:35
  • @ZassX thanks. I think I have tried, but not the Z at the end. Let me try. Commented Oct 5, 2016 at 8:41
  • @ZassX No that didn't worked. To be honest, when I was reading the documentation about the possible values of the formatter, Z wasn't available and I don't know either what that means in a real world date. Commented Oct 5, 2016 at 8:43
  • I have tried using online formatter. This worked OK for me, but that means that date string was a bit different: 2016-08-26T05:16:50-0200 I think that Z in string is not supposed to be there. Also check by yourself: nsdateformatter.com Commented Oct 5, 2016 at 8:50

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Welcome mate :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.