Reputation: 3181
Is there a date formate string for NSDateFormatter that will detect 12 or 24 and 1 or 0 based hour formats?
Unless I'm reading it wrong, the Unicode spec says that one can use the 'j' to this end. For example, the following should use 1-12, 0-23, or 1-24 hours depending on the locale, but NSDateFormatter just creates an empty string.
NSDateFormatter *minuteFormatter = [[NSDateFormatter alloc] init];
minuteFormatter.locale = [NSLocale currentLocale];
minuteFormatter.dateFormat = @"jj";
I've seen many suggesting to use the following to properly interpret the user's locale, but I only want a string with the hour in it, and would rather not have to parse the resulting string.
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
Upvotes: 1
Views: 380
Reputation: 117
from the date format specs:
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).
Which probably means it needs to be resolved before it gets to the date formatting.
Try using + (NSString *)dateFormatFromTemplate:(NSString *)template options:(NSUInteger)opts locale:(NSLocale *)locale
to retrieve a format string.
NSString *format = [NSDate dateFormatFromTemplate:@"jj" options:0 locale: myLocale];
hourFormatter.dateFormat = format;
Upvotes: 4