NSDateFormatter doing wrong

421 Views Asked by At

i'm trying to get my local date and using the NSDateFormatter to write it in the right way, but i'm getting a mix of en_US with pt_BR (portuguese - Brazil). Here the following code:

let br_DateFormat = NSDateFormatter.dateFormatFromTemplate("ddMMMMyyyy", options: 0, locale: NSLocale(localeIdentifier: "pt_BR"))
let date = NSDate();
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = br_DateFormat
let localDate = dateFormatter.stringFromDate(date)
var data = String(localDate)
println(localDate)

What is printed is "11 de June de 2015" What should be printed is "11 de Junho de 2015"

Any ideia what am i doing wrong here?

1

There are 1 best solutions below

0
On BEST ANSWER

You just need to set the locale identifier to "pt_BR"

// this returns the date format string "dd 'de' MMMM 'de' yyyy" but you still need to set your dateFormatter locale later on
let br_DateFormat = NSDateFormatter.dateFormatFromTemplate("ddMMMMyyyy", options: 0, locale: NSLocale(localeIdentifier: "pt_BR")) 
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = br_DateFormat
dateFormatter.locale = NSLocale(localeIdentifier: "pt_BR")
let localDate = dateFormatter.stringFromDate(NSDate())
print(localDate)

You will notice that it will not capitalize the months as you would like to but you can go around this issue as follow:

let localDate = dateFormatter.stringFromDate(NSDate()).capitalizedString.stringByReplacingOccurrencesOfString(" De ", withString: " de ", options: NSStringCompareOptions.LiteralSearch, range: nil)
println(localDate) // "11 de Junho de 2015"