I\'m using a UIDatePicker to select a time. I am also customising the background of the picker, however I need 2 different images depending on whether the user is using 12 hour
Even shorter than the others:
NSString *format = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
BOOL is24Hour = ([format rangeOfString:@"a"].location == NSNotFound);
The string formatting character to represent the am/pm symbol is "a", as documented in Unicode Locale Markup Language – Part 4: Dates.
The same document also explains the special template symbol "j":
This is a special-purpose symbol. It must not occur in pattern or skeleton data. Instead, it is reserved for use in skeletons passed to APIs doing flexible date pattern generation. In such a context, it requests the preferred hour format for the locale (h, H, K, or k), as determined by whether h, H, K, or k is used in the standard short time format for the locale. In the implementation of such an API, 'j' must be replaced by h, H, K, or k before beginning a match against availableFormats data. Note that use of 'j' in a skeleton passed to an API is the only way to have a skeleton request a locale's preferred time cycle type (12-hour or 24-hour).
The NSString
method dateFormatFromTemplate:options:locale:
is described in Apple's NSDateFormatter documentation:
Returns a localized date format string representing the given date format components arranged appropriately for the specified locale.
So, what that method will do is turn the @"j"
you pass in as a template in to a format string suitable for NSDateFormatter
. If this string contains the am / pm symbol @"a"
in it anywhere, then you know the locale (and other user settings being interrogated by the OS for you) wants am / pm to be displayed.