Search code examples
iosswiftdateformatter

Why does converting a Date from a String Object to a Date Object is always nil in Swift


I have the following Date string

2021-08-06T22:46:31+02:00

I am trying to convert it to a Date object using the following code but it is always nil

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyyMMdd'T'HHmmssZ"
    print(dateFormatter.date(from: date) as Any)

In the print statement I get

nil

Solution

  • You're getting nil because your format string cannot match the input string. You need to include the delimiting dashes and colons.

    If you fix the format string, then it will work:

    let fm = DateFormatter()
    fm.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    fm.date(from: str)
    

    Alternatively, as your date is in ISO 8601 format anyway, it's going to be easiest to just use an ISO8601DateFormatter.

    let fm = ISO8601DateFormatter()
    fm.date(from: str)