我以为我最近看到了一些答案,但现在找不到了。这是我现在用来确定设置是否为24小时制显示的代码。它在美国对我有效,但我不知道它是否在所有地区都适用。这是否足够?是否有更好的方法来找出当前的设置?

+(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;

在Swift中:
let formatString: NSString = NSDateFormatter.dateFormatFromTemplate("j", options: 0, locale: NSLocale.currentLocale())!
let hasAMPM = formatString.containsString("a")

swift 4:
let formatString = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)!
let hasAMPM = formatString.contains("a")

这使用称为“j”的特殊日期模板字符串。根据ICU Spec,“j” ...



最后一句话很重要。它“是让骨架请求语言环境的首选时间周期类型的唯一方法”。由于NSDateFormatterNSCalendar是在ICU库上构建的,因此此处同样适用。

关于iphone - 如何确定将iPhone设置为12小时还是24小时显示?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1929958/

10-09 01:23
查看更多