swift – NSDateFormatter在OS X和iOS中检测24小时制

我想检查用户是否在OS X和iOS中选择了12小时或24小时时钟作为他们的偏好.所以我想检测用户是否已完成以下操作:

>在Mac上,系统偏好设置为日期和时间.时间,使用24小时制
>在iPhone上,首选项位于“设置”,“常规”,“日期和时间”中.时间,24小时制

我目前有以下代码,但它总是返回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-C和Swift编写的解决方案,用于Mac和iPhone,它可以检测设备时钟是显示24小时还是12小时.

日期模板功能一个巧妙的技巧.模板说明符j将变为小时格式,具体取决于语言环境是使用12或24小时格式.它会变成像h一样12小时(在这种情况下为en_US)或HH为24小时格式(en_GB).

然后你只需要检查日期格式是否包含

//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")
}

这也应该考虑格式覆盖.

这类似于您的支票,但您不应该尝试检查上午或下午.这些是英文版本,还有更多.例如在德国,如果你强制使用12小时格式iOS使用nachm.和vorm ..正确的方法是检查a的格式.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...