Question

I want to create my custom time format, but I need to know if the user's system preferences want 24 hour or AM/PM format. I've looked through NSCalendar and NSLocale but could not find it.

***UPDATE

Since the other question does not explicitly let us know how to get if the user wants 24-hour time style, I'm answering this question from 2 other questions I found. But still need confirmation if this will work ?

NSString *fmt = [NSDateFormatter dateFormatFromTemplate:@"jm" options:0 locale:[NSLocale currentLocale]];


BOOL is24HourStyle = [fmt rangeOfString:@"HH"].location != NSNotFound;
NSLog(@"%@", fmt);
NSLog(@"is 24 %@", is24HourStyle ? @"YES" : @"NO");
Était-ce utile?

La solution

According to http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns:

  • 'j' is a special purpose symbol for flexible date pattern generation. It requests the preferred hour format for the locale and must be replaced by 'h', 'H', 'K' or 'k'.
  • 'h' and 'K' are symbols for 12-hour-cycle formats.
  • 'H' and 'k' are symbols for 24-hour-cycle formats.

So to check for a 24-hour format, you should check if 'H' or 'k' occurs in the format generated from the template:

NSString *fmt = [NSDateFormatter dateFormatFromTemplate:@"jm" options:0 locale:[NSLocale currentLocale]];
BOOL is24HourStyle = [fmt rangeOfString:@"H"].location != NSNotFound
                  || [fmt rangeOfString:@"k"].location != NSNotFound;

I could not find a locale where the hour format is "k" or "K", but e.g. in the finish locale, "jm" expands to "H.mm", therefore checking for "HH" is not correct.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top