views:

358

answers:

2

How can you detect whether iPhone is displaying time in 12-Hour or 24-Hour Mode?

I currently monitor the current region for changes, however that's not the only setting that affects how times are displayed. The 24-hour toggle in the date & time settings overrides the current regions settings.

Is there any way to detect this 12/14 hour setting?

A: 

Are you using the NSDateFormatter class? As far as I know, that respects whatever regional time-format settings the user has in place.

edit - re: your comment:

The format-string comparison might be the right approach. Something along the lines of:

 NSDateComponents *midnightComp = [[NSDateComponents alloc] init];
 [midnightComp setHour:0]
 [midnightComp setMinute:0];
 NSDateFormatter *format = [[NSDateFormatter alloc] init];
 [format setDateStyle:NSDateFormatterNoStyle];
 [format setTimeStyle:NSDateFormatterShortStyle];
 BOOL midnightIsZeros = [[[format stringFromDate:[[NSCalendar currentCalendar] dateFromComponents:midnightComp]] substringToIndex:2] isEqualToString:@"00"];

 [[NSUserDefaults standardUserDefaults] setBool:midnightIsZeros forKey:@"TimeWas24Hour"];

Run that as your app quits, then do it again when the app launches and check it against the value stored in the defaults.

Noah Witherspoon
I basically need to detect whether that setting has changed since the last load. I can detect the locale identifier, but there's no such setting for the 24 hour setting. Only thing I can think of is to compare a saved formatted date string, but there's issues with timezones and daylight savings which could result issues with direct comparisons.
Michael Waterfall
Thanks for that addition, however I've noticed that several regions actually show hours with 0 in 24 hour mode.
Michael Waterfall
In that case, grab the first two characters as above, and check whether they're either "00" or "0:".
Noah Witherspoon
Not all regions use a colon as the hour/minute delimiter ;-) Pretty tricky. But my answer seems to avoid all of this and it working great. Thanks for your help though!
Michael Waterfall
+2  A: 

I've figured out a decent way of determining this with a little function I've added to a category of NSLocale. It appears to be pretty accurate and haven't found any problems with it while testing with several regions.

@implementation NSLocale (Misc)
- (BOOL)timeIs24HourFormat {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterNoStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    NSString *dateString = [formatter stringFromDate:[NSDate date]];
    NSRange amRange = [dateString rangeOfString:[formatter AMSymbol]];
    NSRange pmRange = [dateString rangeOfString:[formatter PMSymbol]];
    BOOL is24Hour = amRange.location == NSNotFound && pmRange.location == NSNotFound;
    [formatter release];
    return is24Hour;
}
@end
Michael Waterfall