skip to Main Content

I’m having issues converting a string to date on swift, maybe it is something obvious but I don’t get it.

I’m trying to convert "Jan 18, 2022 04:39PM GMT" this string into a Date. My code looks like this:

let str = "Jan 18, 2022 04:39PM GMT"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d, YYYY hh:mma z"

let date = dateFormatter.date(from: str)
print(date)

And console shows: Optional(2021-12-19 16:39:00 +0000)

Any idea what’s wrong in this formatter?

2

Answers


  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
    }
    
    Login or Signup to reply.
  2. The code written for converting date is correct, also converted date is correct. But final result is optional so you are getting date like Optional(2021-12-19 16:39:00 +0000).
    Also the date formatter is wrong.
    So please unwrap the date to get actual date without optional.

    dateFormatter.dateFormat = "MMM d, yyyy hh:mma z"
    guard let convertedDate = date else {
    return
    }
    print(convertedDate)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search