问题
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?
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/1972108/detect-whether-iphone-is-displaying-time-in-12-hour-or-24-hour-mode