获取时间周期类型(12 小时或 24 小时)

检查当前日期是否包含 AM 或 PM 的符号

Objective-C

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]];
BOOL is24h = (amRange.location == NSNotFound && pmRange.location == NSNotFound);

NSDateFormatter 请求时间周期类型

Objective-C

NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
NSRange containsA = [formatStringForHours rangeOfString:@"a"];
BOOL is24h = containsA.location == NSNotFound;

这使用了一个名为 j 的特殊日期模板字符串,根据 ICU Spec

[…]请求区域设置(h,H,K 或 k)的首选小时格式,由补充数据中小时元素的首选属性确定。 […]请注意,在传递给 API 的骨架中使用’j’是让骨架请求区域设置的首选时间周期类型(12 小时或 24 小时)的唯一方法。

最后一句很重要。它是骨架请求区域设置首选时间周期类型的唯一方法。由于 NSDateFormatterNSCalendar 是建立在 ICU 库上的,所以这里也是如此。

参考

第二个选项来自这个答案