Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)!)
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading