Search code examples
iosswiftnsdateformatterdate-formattingnslocale

Reformat localized date string to another locale


I have a String that is "Jueves 14 Junio 1990": it is a date formatted in the es_MX locale, I want to convert that into a new string with en_US as the locale.

This is my code:

let myString:String = "Jueves 14 Junio 1990"

let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
dateFormatter.dateFormat = "EEEE dd MMMM yyyy"
let finalDate:NSDate = dateFormatter.dateFromString(myString)!
let finalString = dateFormatter.stringFromDate(date)

I was waiting that finalString resulted as Thursday 14 June 1990.

The problem here is that finalDate is nil.

Is my code wrong? How can I achieve this?


Solution

  • You have to use es_MX locale first to convert the string to NSDate:

    let string = "Jueves 10 Junio 1990"
    let formatter = NSDateFormatter()
    formatter.dateFormat = "EEEE dd MMMM yyyy"
    formatter.locale = NSLocale(localeIdentifier: "es_MX")
    if let date = formatter.dateFromString(string) {
        formatter.locale = NSLocale(localeIdentifier: "en_US")
        let dateString = formatter.stringFromDate(date)
    }