I am building an alarm clock app in Swift 2. I can't seem to find a decent way to find out whether the phone is set to 24 hours time or not. In addition I can't change the simulator to work with 24 hours so I can't even test some alternatives by playing with the time settings. Any ideas?
Asked
Active
Viewed 8,875 times
1 Answers
53
- There is a template specifier for
NSDateFormatter
that fits this need. This specifier isj
and you can get it through thedateFormatFromTemplate:options:locale:
method ofNSDateFormatter
. The formatter returnsh a
if the locale is set to 12H, elseHH
if it's set to 24H, so you can easily check if the output string containsa
or not. This relies on thelocale
property of the formatter that you should set toNSLocale.currentLocale()
for getting the system's current locale:
Swift 3
let locale = NSLocale.current
let formatter : String = DateFormatter.dateFormat(fromTemplate: "j", options:0, locale:locale)!
if formatter.contains("a") {
//phone is set to 12 hours
} else {
//phone is set to 24 hours
}
Swift 2
let locale = NSLocale.currentLocale()
let formatter : String = NSDateFormatter.dateFormatFromTemplate("j", options:0, locale:locale)!
if formatter.containsString("a") {
//phone is set to 12 hours
} else {
//phone is set to 24 hours
}
Reference: NSDateFormatter Class Reference - Unicode ts35-23 Date Field Symbol Table
- In the simulator, you don't have the 12/24 hours toggle in the settings like it happens on the real devices. A trick for changing this is by editing the date style of the Simulator, without affecting the currently selected region or calendar. You can find this option in Settings > General > Language and Region > Advanced.

Alexander Poleschuk
- 892
- 12
- 22

Nicola Giancecchi
- 3,045
- 2
- 25
- 41
-
1for 24 hours format the result should contains HH ... So or so, template "j" is very useful information, at least for me. Are you able to share some reference to that? – user3441734 Jan 23 '16 at 16:41
-
@user3441734 you're right, for 24 hours format the result is "HH" and for 12 hours is "h a". I've edited the answer and I added references to NSDateFormatter and the associated Unicode standard. – Nicola Giancecchi Jan 23 '16 at 18:15
-
thanks for the reference! – user3441734 Jan 23 '16 at 18:21
-
Worked like a charm! thanks a lot for this!! – Ran Jan 25 '16 at 06:44