使用 swift,我希望我的自定义 dateFormatter.dateFormat 是 MMM-d 或 d-MMM,具体取决于用户的位置。如果我使用默认的 short.medium.etc 样式,这似乎很容易,但出于设计/布局方面的考虑,我需要这种自定义格式。
有什么帮助吗?
最佳答案
您可以读取当前设备区域设置并相应地设置格式。
var dateFormat: String
switch NSLocale.currentLocale().localeIdentifier {
case "en_US": dateFormat = "MMM d"
...
default: dateFormat = "d MMM"
}
另请查看 NSDateFormatter.dateFormatFromTemplate
:
NSDateFormatter.dateFormatFromTemplate("MMM dd", options: 0, locale: NSLocale.currentLocale())
它返回适用于由您指定的元素(在本例中为月和日)组成的给定语言环境的格式和顺序,但它并不总是您需要的“MMM d”或“d MMM”。您可以运行它来查看它为每个语言环境实际生成的字符串:
let formatter: DateFormatter = DateFormatter()
for id in NSLocale.availableLocaleIdentifiers {
let locale = NSLocale(localeIdentifier: id)
let format = DateFormatter.dateFormat(fromTemplate: "MMM dd", options: 0, locale: locale as Locale) ?? "n/a"
formatter.dateFormat = format
formatter.locale = locale as Locale!
let fd = formatter.string(from: NSDate() as Date)
print("\(id)\t\(format)\t\(fd)")
}
关于swift - 自定义本地日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31632545/