Search code examples
swiftdatedateformatter

Unable to change format of date in swift


I am getting date 2019-01-02 18:10:00 +0000 like this now i want to convert it to dd/MM/yyyy HH:mm format but i'm unable to get it.

I am using this method in date extension

func getDate() -> Date {
    let formatter = DateFormatter()
    formatter.timeZone = TimeZone(abbreviation: "UTC")
    formatter.dateFormat = "dd/MM/yyyy HH:mm"
    let dateString = formatter.string(from: self)
    return formatter.date(from: dateString) ?? Date()
}

when xcode executes this line

let dateString = formatter.string(from: self)

the result is in format which i want but when last line gets executed date returns back to the old formate


Solution

  • You are doing it wrong. If you need to show the date, you use a formatted String and not the Date object.

    func getDate() -> String {
        let formatter = DateFormatter()
        // Set the appropriate time zone or locale
        formatter.dateFormat = "dd/MM/yyyy HH:mm"
        return formatter.string(from: self)
    }