NSDateFormatter 做错了

NSDateFormatter doing wrong

我正在尝试获取我的本地日期并使用 NSDateFormatter 以正确的方式编写它,但我得到的是 en_US 和 pt_BR 的混合(葡萄牙语 - 巴西) . 下面是代码:

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)

打印的是“11 de June de 2015” 应该打印的是“11 de Junho de 2015”

知道我做错了什么吗?

您只需将语言环境标识符设置为"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)

您会注意到它不会像您希望的那样将月份大写,但您可以按以下方式解决此问题:

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