Sha*_*ane 3 localization internationalization date-formatting swift
使用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"
}
Run Code Online (Sandbox Code Playgroud)
另外看看NSDateFormatter.dateFormatFromTemplate:
NSDateFormatter.dateFormatFromTemplate("MMM dd", options: 0, locale: NSLocale.currentLocale())
Run Code Online (Sandbox Code Playgroud)
返回适用于给定语言环境的格式和顺序,包括您指定的元素(本例中为月份和日期),但并不总是根据需要使用"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)")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6612 次 |
| 最近记录: |