Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 829
iParesh Avatar asked Jul 21 '16 11:07

iParesh


2 Answers

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 and later

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let date = dateFormatter.date(from: date)
dateFormatter.dateFormat = "yyyy-MM-dd"
let resultString = dateFormatter.string(from: date!)
print(resultString)
like image 109
Nirav D Avatar answered Sep 22 '22 10:09

Nirav D


You can define a function like the one below:

// input string should always be in format "21/07/2016" ("dd/MM/yyyy")

func formattedDateFromString(dateString: String, withFormat format: String) -> String? {

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

    if let date = inputFormatter.dateFromString(dateString) {

      let outputFormatter = NSDateFormatter()
      outputFormatter.dateFormat = format

      return outputFormatter.stringFromDate(date)
    }

    return nil
}

You can use the above to pass an output format for your date string. Input format will always be dd/MM/yyyy. Then you use it as follows:

let stringA = formattedDateFromString("21/07/2016", withFormat: "yyyy-MM-dd")
let stringB = formattedDateFromString("21/07/2016", withFormat: "MMM dd, yyyy")

NSLog("stringA: \(stringA)") // 2016-07-21
NSLog("stringB: \(stringB)") // Jul 21, 2016
like image 35
ahmedomer Avatar answered Sep 20 '22 10:09

ahmedomer