How to convert date format from dd/MM/YYYY to YYYY-MM-dd in swift

iParesh picture iParesh · Jul 21, 2016 · Viewed 53.9k times · Source

I tired to covert from 21/07/2016 to 2016-07-21 but got this date 2015-12-20
Here is the Code that i have try

let inputFormatter = NSDateFormatter()
inputFormatter.dateFormat = "MM/dd/YYYY"

let outputFormatter = NSDateFormatter()
outputFormatter.dateFormat = "YYYY-MM-dd"

let showDate = inputFormatter.dateFromString("07/21/2016")
let resultString = outputFormatter.stringFromDate(showDate!)

print(resultString)

How to convert?
Thank you

Answer

Nirav D picture Nirav D · Jul 21, 2016

First changes your year formatter with yyyy and instead of using two NSDateFormatter use just one like this

let inputFormatter = NSDateFormatter()
inputFormatter.dateFormat = "MM/dd/yyyy"
let showDate = inputFormatter.dateFromString("07/21/2016")
inputFormatter.dateFormat = "yyyy-MM-dd"
let resultString = inputFormatter.stringFromDate(showDate!)
print(resultString)

For swift3

func convertDateFormater(_ date: String) -> String
    {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
        let date = dateFormatter.date(from: date)
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return  dateFormatter.string(from: date!)

    }