swiftnsdatensdateformatter

NSDateFormatter detect 24-hour clock in OS X and iOS


I would like to check if the user has selected the 12-hour or 24-hour clock as their preference in OS X and iOS. So I would like to detect if the user has done the following:

I currently have the following code but it always returns the time as represented by the 12-hour clock, even if the system preference set by the user is for the 24-hour clock.

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

I would like to find a solution written in Objective-C and Swift for both the Mac and iPhone that can detect if the device clock displays 24-hour or 12-hour time.


Solution

  • The date template function has a neat trick. There is a template specifier j which will turn into an hour format depending if the locale uses 12 or 24 hour format. It'll turn into something like h a for 12 hour (en_US in this case) or HH for 24 hour format (en_GB).

    Then you just have to check if the date format contains 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")
    }
    

    This should take format overwrites into account as well.

    This is similar to your check, but you should not try to check for AM or PM. These are the english versions, there are many more. For example in Germany if you force a 12 hour format iOS uses nachm. and vorm.. The correct way is to check the format for a.