Dipak Dhondge Dipak Dhondge - 28 days ago 19
iOS Question

Converting String to Date using dd-MM-yyyy get nil in Xcode 8 in Swift 3.0

if I choose date like

let dateString = "2014-01-12"
, How would I convert string to

dateFormatter.dateFormat = "yyyy-MM-dd"


and then in below format

dateFormatter.dateFormat = "dd-MM-yyyy"


I get nil values in Xcode 8 in Swift 3.0

{

let dateString = "2014-01-12"
dateFormatter.locale = Locale(identifier:"ja_JP")
dateFormatter.dateFormat = "dd-MM-yyyy"
print(dateFormatter.date(from:dateString))
}


or

let dateString = "2014-01-12"

dateFormatter.dateFormat = "yyyy-MM-dd"
var s = dateFormatter.date(from: dateString)! as Date

dateFormatter.dateFormat = "dd-MM-yyyy"

s = dateFormatter.date(from: dateString)! as Date
print("SecondDate\(s)")


In Xcode 7 it works fine.

Answer

Need to change date string into "date string" as Date then you can change into your particular format. For every format you need to do this first.

You can use the code below.

Swift 3

extension String {
    func changeDate(_ mydate:String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = DateFormatter.Style.long
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let convertedDate = dateFormatter.date(from: mydate)
        dateFormatter.dateFormat = "dd-MM-yyyy"
        let date = dateFormatter.string(from: convertedDate!)
        return date
    }
}