我想检查用户是否选择了12小时或24小时时钟作为他们在OS和iOS中的首选。因此,我想检测用户是否做了以下操作:
我目前有以下代码,但它总是返回12小时时钟所表示的时间,即使用户设置的系统首选项是24小时时钟。
let timeFormatter = NSDateFormatter()
timeFormatter.locale = NSLocale.currentLocale()
timeFormatter.dateStyle = NSDateFormatterStyle.NoStyle
timeFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
let ampmtext = timeFormatter.stringFromDate(NSDate())
println(ampmtext)
if ampmtext.rangeOfString("M") != nil {
println("12-hour clock")
} else {
println("24-hour clock")
}我想找到一个用Objective和Swift为Mac和iPhone编写的解决方案,它可以检测设备时钟是显示24小时还是12小时。
发布于 2015-01-28 01:32:33
日期模板函数有一个巧妙的技巧。有一个模板说明符j,它将根据区域设置是否使用12小时或24小时格式而转换为一小时格式。它将变成类似于h a 12小时(本例中为en_US)或HH为24小时格式(en_GB)。
然后,您只需检查日期格式是否包含a
//let locale = NSLocale(localeIdentifier: "de_DE")
//let locale = NSLocale(localeIdentifier: "en_US")
//let locale = NSLocale(localeIdentifier: "en_GB")
let locale = NSLocale.currentLocale()
let dateFormat = NSDateFormatter.dateFormatFromTemplate("j", options: 0, locale: locale)!
if dateFormat.rangeOfString("a") != nil {
println("12 hour")
}
else {
println("24 hour")
}这也应该考虑到覆盖格式。
这类似于您的检查,但您不应该尝试检查AM或PM。这些都是英文版本,还有更多。例如,在德国,如果强制使用12小时格式,iOS使用nachm.和vorm.。正确的方法是检查a的格式。
发布于 2018-03-22 21:17:45
Swift 4
以下是对已被接受的答案的快速4种解释:
func is24Hour() -> Bool {
let dateFormat = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)!
return dateFormat.firstIndex(of: "a") == nil
}用法:
if is24Hour() {
// should show 24 hour time
} else {
// should show 12 hour time
}发布于 2021-11-08 08:42:22
使用此扩展程序
extension Locale {
static var is24Hour: Bool {
let dateFormat = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)!
return dateFormat.firstIndex(of: "a") == nil
}
}免费在任何地方使用
if Locale.is24Hour {
// Show 24 hour time
} else {
// Show 12 hour time
}https://stackoverflow.com/questions/28162729
复制相似问题