Home > Back-end >  Converting Date String to different Format
Converting Date String to different Format

Time:10-29

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?

CodePudding user response:

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

  • Related