Wednesday, February 9, 2011

How to tell if the user's using 24 hour time using Cocoa

I'm trying to determine if the user is using 24 hour or 12 hour time, and there doesn't seem to be a good way to figure this out other than creating an NSDateFormatter and searching the format string for the period field ('a' character)

Here's what I'm doing now:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSRange range = [[formatter dateFormat] rangeOfString:@"a"];
BOOL is24HourFormat = range.location == NSNotFound && range.length == 0;
[formatter release];

Which works, but feels kinda fragile. There has to be a better way, right?

  • This information is provided in NSUserDefaults. Maybe under the NSShortTimeDateFormatString key? (Still requires parsing of course).

    (Use

    NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
    

    to dump all the pre-defined user defaults).

    Not quite sure why you want to do this - I bet you have a good reason - but maybe it's best just to use the defaults in NSDateFormatter instead?

    From schwa
  • NSShortTimeDateFormatString is deprecated, and I believe it also effectively doesn't work in 10.5 and later. See the 10.4 and 10.5 Foundation release notes. Dumping all defaults is a good way to depend on stuff that is not guaranteed by the interface, though it can be interesting to sort of see what's going on under the hood.

    Why do you need this? As schwa says, everything works much better if you can get away from needing to know anything about the localized presentation.

    From Ken

0 comments:

Post a Comment