1

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

1 Answer 1

1

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"))
Sign up to request clarification or add additional context in comments.

2 Comments

Can you make a little changes of the return? because i need it return as date Try to directly "return date" but the output is minus 1 day from what is should be
i add this and it works "formatter.timeZone = TimeZone(abbreviation: "GMT")"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.