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

Converting Date String to different Format

I have myString "28-OCT-22"
I need to convert it to different format "dd.MM.yyyy"
What I’ve tried:

let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = "d-MMM-yy"
                    let date = dateFormatter.date(from: myString)! //error, I think because OCT is uppercase, NSDateFormatter doesn't have this format?
                    dateFormatter.dateFormat = "dd.MM.yyyy"
                    let stringDate = dateFormatter.string(from: date)

and is there more clean way to do this?

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

>Solution :

Month abbreviations are localized.

Set the locale to the fixed generic value en_US_POSIX which supports OCT

let myString = "28-OCT-22"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "d-MMM-yy"
let date = dateFormatter.date(from: myString)!
dateFormatter.dateFormat = "dd.MM.yyyy"
let stringDate = dateFormatter.string(from: date)

Although the format is correct force unwrapping converted dates is not recommended

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