我的 iOS 应用程序会将时间从时间戳格式化为时间字符串。我想在应用程序中提供一个设置,它将覆盖系统的 12/24 小时格式。
我尝试了什么:
self.timeFormatter.timeStyle = NSDateFormatterStyle.ShortStyle;
let locale:NSLocale = NSLocale.currentLocale();
if(Constants.isFormat12()){
timeFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("hh:mm", options: 0, locale: locale);
}else{
timeFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("HH:mm", options: 0, locale: locale);
}
如果系统低于 12 小时格式,但不是 24 小时格式,此代码将起作用。
我在 stackoverflow 上阅读了一些帖子,他们建议设置 to 的语言环境,NSDateFormatter
以便en_US_POSIX
时间en_GB
格式为 12 或 24 小时格式。
if(Constants.isFormat12()){
timeFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX");
timeFormatter.dateFormat = "hh:mm a";
}else{
timeFormatter.locale = NSLocale(localeIdentifier: "en_GB");
timeFormatter.dateFormat = "HH:mm";
}
但是,12 小时格式将显示AM
和PM
,而不是不同语言的本地化版本“AM”和“PM”,例如中文的“上午”和“下午”。
有什么方法可以强制 NSDateFormatter 使用 12/24 小时吗?