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
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With