gpt4 book ai didi

swift - NSDateFormatter 做错了

转载 作者:行者123 更新时间:2023-11-28 13:12:37 30 4
gpt4 key购买 nike

我正在尝试获取我的本地日期并使用 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"

关于swift - NSDateFormatter 做错了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30791052/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com