I've got a drawRect that makes a timeline a bit like iCal. I use a for loop to write the times along a scroll view. I was wondering if A) theres a way of determining whether the user has chosen a 12 or 24 hour clock in the system settings and B) if there is a more efficient way of changing the time labels then calling an 'if' query every pass of the 'for' loop. Cheers
Asked
Active
Viewed 2,094 times
5
-
You need to be careful. If the user has set 12/24 hour mode in Settings contrary to the locale, then NSDateFormatter (and likely some others) ignore the presence/absence of any `a` qualifier and provide (or not) the AM/PM value based on the 12/24 hour mode setting. It's all quite screwy. – Hot Licks May 13 '14 at 01:14
3 Answers
6
The earlier answers assume that the "AM" and "PM" symbols are represented in roman characters. This code adapted from keyur bhalodiya does a better job at handling languages like Chinese, by using the AMSymbol
and PMSymbol
methods of NSDateFormatter
.
-(BOOL)uses24hourTime
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateStyle:NSDateFormatterNoStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSRange amRange = [dateString rangeOfString:[formatter AMSymbol]];
NSRange pmRange = [dateString rangeOfString:[formatter PMSymbol]];
return (amRange.location == NSNotFound && pmRange.location == NSNotFound);
}

Community
- 1
- 1

William Denniss
- 16,089
- 7
- 81
- 124
5
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
if([[dateFormatter dateFormat] rangeOfString:@"a"].location != NSNotFound) {
// user prefers 12 hour clock
} else {
// user prefers 24 hour clock
}

Amy Worrall
- 16,250
- 3
- 42
- 65
-
2This is actually the best answer, since many countries specify AM and PM as a.m. and p.m.. – MiguelB Jan 04 '12 at 17:16
-
1@Leuguimerius but some languages like Chinese use totally different characters for AM and PM. See my answer http://stackoverflow.com/a/23621308/72176 for how to handle that. – William Denniss May 13 '14 at 01:12
-
@WilliamDenniss Brilliant! Solves everything. I had no idea such formatter existed. – MiguelB May 17 '14 at 18:36
1
NSDate *today = [NSDate date];
NSString *formattedString = [NSDateFormatter localizedStringFromDate:today dateStyle: kCFDateFormatterNoStyle timeStyle: kCFDateFormatterShortStyle];
NSRange foundRange;
foundRange = [formattedString rangeOfString:"am" options:NSCaseInsensitiveSearch];
if(foundRange.location == NSNotFound) {
foundRange = [formattedString rangeOfString:"pm" options:NSCaseInsensitiveSearch];
}
BOOL isAMPMSettingOn = (foundRange.location != NSNotFound);

Denis
- 6,313
- 1
- 28
- 27