Convert string containing date to Date

Solution 1:

In addition to the Date being shown as an Optional, your format string appears to be wrong. "YYYY" should be "yyyy", so the whole line that assigns the formatter should be:

dateFormatter.dateFormat = "MMM d, yyyy hh:mma z"

That change yields the output

"Optional(2022-01-18 16:39:00 +0000)"

In addition, you should really force the calendar to Gregorian or iso8601, and set its locale to "en_US_POSIX:

An improved version of the date formatter could would look like this:

(from Leo's edit.)

let str = "Jan 18, 2022 04:39PM GMT"
let dateFormatter = DateFormatter()
dateFormatter.calendar = .init(identifier: .iso8601)
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "MMM d, yyyy hh:mma z"

if let date = dateFormatter.date(from: str) {
    let dateString = dateFormatter.string(from: date)
    print(dateString == str)  // true
}