0

I got a date string from server side, which is Tue, 28 May 2019 13:24:06 +0000. I tried to do following:

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
let date = dateFormatter.date(from: "Tue, 28 May 2019 13:24:06 +0000")

result is nil

How can I convert a string like this to a Date?

2
  • 1
    You probably need to specify a custom date/time format Commented May 29, 2019 at 6:29
  • You may also want to look at nsdateformatter.com for reference Commented May 29, 2019 at 6:31

1 Answer 1

5

You need to set a specific dateFormat. And when doing so, set the date formatter's locale to en_US_POSIX.

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
let date = dateFormatter.date(from: "Tue, 28 May 2019 13:24:06 +0000")

See the documentation for dateFormat for links that take you a full description of what all of the format specifiers mean.

Keep in mind that when converting a Date to a String for display to the user, then using date and time styles is the best solution. But for parsing a String into a Date, use dateFormat.

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

4 Comments

It worked, even without specifying local. Thanks. Is there any generic approach to parse any type of date string? Let's say, user add a new rss feed which I couldn't know the type of date string from this new feed in advance
You need to specify this special locale, otherwise your code will fail for many users, especially if their device is setup for a non-English language.
Look into NSDataDetector as a possible way to handle strings with unknown date formats.
All right. I will look into NSDataDetector , and specify locale in my code. Thanks again!

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.