Detect whether iPhone is displaying time in 12-Hour or 24-Hour Mode?

微笑、不失礼 提交于 2019-11-28 08:38:49

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!