Search code examples
swiftdateformatter

Swift Convert date string to Date


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?


Solution

  • 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.