Search code examples
iosswiftnsdateformatter

Issue in converting date format


I have assigned the value of date to a dictionary like so...

userDetailsDictionary["birth_date"] = "\(birthDateVar)"

Now this gives the date in dd-mm-yyyy. But I want the date in yyyy-mm-dd. For that I tried something like this...

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let bday = dateFormatter.date(from: birthDateVar)
dateFormatter.dateFormat = "yyyy-MM-dd"
let bdayString = dateFormatter.string(from: bday!)

Though birthDateVar has the value in it, while I'm trying to convert it, it is showing as nil and so bday is becoming nil. Confused as to what the reason is...


Solution

  • change your date format from

    dateFormatter.dateFormat = "MM-dd-yyyy"
    

    to

    dateFormatter.dateFormat = "dd-MM-yyyy"
    

    Updated answer

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy"
    dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
    let bday = dateFormatter.date(from: birthDateVar)
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let bdayString = dateFormatter.string(from: bday!)