Detect 24-Hour User Settings on iOS Devices

Article summary

Apple’s date formatters are powerful. They adjust to the user’s locale as well as “24 hour” clock settings. Most of the time, it is sufficient to use an NSDateFormatter to display a time to the user. There are a few situations, however, where it is nice to use custom formatting. It would be nice to still conform to the user’s “24 hour” clock settings when this is necessary.

One scenario is displaying “Noon” instead of “12 p.m.”. But if the user has selected “24 hour” clock, they would expect to see “12:00” to be consistant with their other times.

As far as I know, Apple does not supply a way to access the user’s “24 hour” setting directly. I wrote a category of NSCalendar that uses a date formatter to detect the user’s setting. The code uses a default formatter to format a date with a time at “10 p.m.” and checks to see if it begins with a “2”.

Interface

#import <Foundation/Foundation.h>

@interface NSCalendar(Extensions)
+ (BOOL)prefers24Hour;
@end

Implementation

#import "NSCalendar+Extensions.h"

@implementation NSCalendar(Extensions)

+ (BOOL)prefers24Hour {
  NSDateComponents *comps = [[NSDateComponents alloc] init];
  [comps setHour:22];
  NSDate *testDate = [[self currentCalendar] dateFromComponents:comps];
  static NSDateFormatter *formatter;
  if (!formatter) {
    formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeStyle:kCFDateFormatterShortStyle];
  }
  NSString *testString = [formatter stringFromDate:testDate];
  [comps release];
  return [[testString substringToIndex:1] isEqualToString:@"2"];
}

@end
Conversation
  • Peter says:

    Just wanted to say thanks for sharing this, exactly what I was looking for. Cheers!

  • paul says:

    in your code:
    return [[testString substringToIndex:1] isEqualToString:@”2″];

    Arabic region format does not use “2”. It is more subtle problem than it looks.

  • Comments are closed.