Home > Net >  Swift String to date conversion found nil while unwrapping an Optional value
Swift String to date conversion found nil while unwrapping an Optional value

Time:08-15

I'm receiving a PST date inside a string in the following format "2022-08-14 13:45:39 America/Los_Angeles" and I'm trying to convert it to a real date using the code below which is causing the fatal error Fatal error: Unexpectedly found nil while unwrapping an Optional value. I'm struggling to understand how it doesn't know that this is a date given the format. The code is inside an extension block and I'm calling it like "".stringToDate.

var stringToDate: Date {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        let date = dateFormatter.date(from: self)
        print("NEW DATE! \(date)")
        return date! // Here is where Xcode states the error is
}

CodePudding user response:

Your format string does not include the timezone ID "America/Los_Angeles", so it fails to parse your string.

According to here, the format pattern for parsing IDs like that is apparently VV.

Therefore, you should change to:

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss VV"

and the output would be:

NEW DATE! Optional(2022-08-14 20:45:39  0000)

which is the correct instant. 1pm in LA in the summer is 8pm UTC.

  • Related