如何确定 iPhone 设置为 12 小时还是 24 小时时间显示? [英] How can I determine if iPhone is set for 12 hour or 24 hour time display?
问题描述
我以为我最近在 SO 上看到有人在回答这个问题,但现在我找不到了.这是我现在用来确定设置是否用于 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;
在斯威夫特中:
let formatString: NSString = NSDateFormatter.dateFormatFromTemplate("j", options: 0, locale: NSLocale.currentLocale())!
let hasAMPM = formatString.containsString("a")
斯威夫特 4:
let formatString = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)!
let hasAMPM = formatString.contains("a")
这使用称为j"的特殊日期模板字符串.根据 ICU 规范,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 的实现中,在开始与 availableFormats 数据进行匹配之前,必须将j"替换为 h、H、K 或 k.请注意,在传递给 API 的框架中使用j"是让框架请求语言环境的首选时间周期类型(12 小时或 24 小时)的唯一方法.
requests the preferred hour format for the locale (h, H, K, or k), as determined by whether h, H, K, or k is used in the standard short time format for the locale. In the implementation of such an API, 'j' must be replaced by h, H, K, or k before beginning a match against availableFormats data. Note that use of 'j' in a skeleton passed to an API is the only way to have a skeleton request a locale's preferred time cycle type (12-hour or 24-hour).
最后一句话很重要.它是让骨架请求语言环境的首选时间周期类型的唯一方法".由于 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 小时时间显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!