Search code examples
swiftnsdateformatter

How to convert a String of certain format to Date in Swift?


I have strings like this 2020-09-21T21:13:55.636Z... I want to convert them into Dates and here's what I do;

func convertToDate(str: String) -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

    return dateFormatter.date(from: str)!
}

The above code crashes on the unwrapping. I'm guessing it's because of the format... Any idea what I'm doing wrong?


Solution

  • For that date string you should use ISO8601DateFormatter, like this:

    var str = "2020-09-21T21:13:55.636Z"
    
    let formatter = ISO8601DateFormatter()
    formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
    let date = formatter.date(from: str)
    

    That will save you the trouble of trying to get a format string exactly right.