Home > OS >  How to change date format from dd MMMM YYYY in swift?
How to change date format from dd MMMM YYYY in swift?

Time:03-15

I need date to be convert from dd MMMM YYYY to dd-mm-yyyy.

e.g. : (01 August 2021) -> 01-09-2021

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "dd-MM-yyyy"
print( dateFormatter.date(from:response.data?[0].mbStartDate ?? ""))

The output is nil.

I've make sure that response data value is exist

How to convert it ?

And How to change "01 August 2021" to other languange? My case is change it to indonesian. So it becomes "01 Agustus 2021". How to do this too?

Thanks before

CodePudding user response:

Using DateFormatter is right way to do. First you need to convert the 01 August 2021 , String type, to Date object. Second, change dateFormat and re-format it. Here is tested code for both of your need:

func convert(_ dateString: String, from initialFormat: String, to targetFormat: String? = nil, _ locale: Locale? = nil) -> String? {
    let formatter = DateFormatter()
    formatter.dateFormat = initialFormat
    guard let date = formatter.date(from: dateString) else { return nil }
    
    if let newFormat = targetFormat {
        formatter.dateFormat = targetFormat
    }
    formatter.locale = locale
    return formatter.string(from: date)
}

print(convert("01 August 2021", from: "dd MMMM yyyy", .init(identifier: "id_ID")))
print(convert("01 August 2021", from: "dd MMMM yyyy", to: "dd-MM-yyyy"))
  • Related