Home > Enterprise >  How can I format a specific string "05-Jan-2022 12:05 AM" to a date object in Swift?
How can I format a specific string "05-Jan-2022 12:05 AM" to a date object in Swift?

Time:05-28

I've tried using this piece of code, works fine in playground but crashes the app in actual project.

let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MMM-yyyy HH:mm a"
    
    let dates = [
        "05-Jan-2022 12:00 AM",
        "11-Nov-2021 12:00 AM",
        "11-Nov-2021 12:00 AM",
        "08-Oct-2021 03:04 PM",
        "08-Oct-2021 12:00 AM",
        "30-Sep-2021 03:48 PM"
    ]
    
    dates.forEach { date in
        print(dateFormatter.date(from: date)!)
    }

CodePudding user response:

Two issues:

  • You have to set the locale to fixed en_US_POSIX

  • 12 hr format is hh

    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "dd-MMM-yyyy hh:mm a"
    
  • Related