问题描述
我以为我最近看到了很多东西在回答这个问题,但现在我找不到了。以下是我现在使用的代码来确定24小时时间显示的设置。它适用于我在美国,但我不知道它是否会在所有地区工作。这是否足够或有更好的方法来找出目前的设置?
I thought I saw something answering this on SO recently but now I can't find it. Here is the code I am using now to determine if settings are for 24 hour time display. It works for me in the US, but I don't know if it will work in all locales. Is this sufficient or is there a better way to find out the current setting for this?
+(BOOL) use24HourClock
{
BOOL using24HourClock = NO;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale: [NSLocale currentLocale]];
[dateFormatter setDateStyle:kCFDateFormatterNoStyle];
[dateFormatter setTimeStyle:kCFDateFormatterShortStyle];
// get date/time (1Jan2001 0000UTC)
NSDate* midnight = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:0];
NSString* dateString = [dateFormatter stringFromDate: midnight];
// dateString will either be "15:00" or "16:00" (depending on DST) or
// it will be "4:00 PM" or "3:00 PM" (depending on DST)
using24HourClock = ([dateString length] == 5);
[midnight release];
[dateFormatter release];
return using24HourClock;
}
推荐答案
这是最好的方法它:
NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
NSRange containsA = [formatStringForHours rangeOfString:@"a"];
BOOL hasAMPM = containsA.location != NSNotFound;
in Swift:
let formatString: NSString = NSDateFormatter.dateFormatFromTemplate("j", options: 0, locale: NSLocale.currentLocale())!
let hasAMPM = formatString.containsString("a")
这使用一个特殊的日期模板字符串叫做j。根据,j...
This uses a special date template string called "j". According to the ICU Spec, "j"...
请求用于区域设置(h,H,K或k)的首选小时格式,由h,H,K或k是否以标准短时间格式使用区域设置在这种API的实现中,在开始与可用格式数据的匹配之前,'j'必须由h,H,K或k代替。请注意,传递给API的框架中使用'j'是让框架请求具有语言环境首选时间周期类型(12小时或24小时)的唯一方法。
最后一句很重要。它是使框架请求语言环境首选时间周期类型的唯一方法。由于 NSDateFormatter
和 NSCalendar
建立在ICU库中,同样适用于此。
That last sentence is important. It "is the only way to have a skeleton request a locale's preferred time cycle type". Since NSDateFormatter
and NSCalendar
are built on the ICU library, the same holds true here.
这篇关于iPhone如何确定是否设置了12小时或24小时的时间显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!