I'm trying to figure out whether or not the current locale uses a 12 hour or a 24 hour clock. I've been checking out NSDateFormater to no avail. Any leads?
Thanks!
I'm trying to figure out whether or not the current locale uses a 12 hour or a 24 hour clock. I've been checking out NSDateFormater to no avail. Any leads?
Thanks!
This isn't a locale setting so much as a collection of locale settings. It's part of the time formats, of which there are four (on the Mac, at least), which do not all necessarily use the same AM/PM designation. On the Mac, it's even possible to use a 24-hour hour segment with an AM/PM segment, for output like “17:35 PM”—silly, but possible nonetheless.
The simplest way is to just ask the date formatter to format the time from the date object for you, assuming that that makes sense for what you're doing. If not, fun times are headed your way.
On the iPhone, the UI for the format strings is just a toggle switch (24-hour, on or off), so you shouldn't have to worry about pathological cases. Pick one of the format strings in AppleICUTimeFormatStrings
in user defaults, then parse it, looking for one of the AM/PM format characters. Make sure to skip over anything between ''
, as that content is a literal string, not format characters.
Just watch out if you ever bring your app to the Mac. If you do, I wouldn't bother trying to make sense of the format strings—just make it a checkbox in your own Preferences.
Your best bet is definitely to just do [someNSDateFormatter stringFromDate:someDate] or [someNSDateFormatter dateFromString:someString], but if you really want to do what you're asking about, take a look at the Unicode standard for date format strings, which is what iPhone OS uses.
In particular, note that a is used for the AM/PM symbol and h/hh/H/HH/k/KK are all possibilities for the hour symbol, depending on if it counts from 0 or 1, is 12 or 24 hour, and pads with zeroes or not.
Your code to implement this might be something along the lines of:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
if([[dateFormatter dateFormat] containsString:@"a"]) {
// do something
} else {
// do something else
}
[dateFormatter release];
But, you have to be careful because literal characters can be contained in single quotes, so you'd have to account for that. You could try looking for h or k, but watch out because the French represent 2:05 pm as 14h05 (not sure if that's how it shows up on the iPhone, but that's how they'll often write it), so the time format might include something like k'h'mm