Ste*_*ear 1 iphone xcode objective-c nsdate nsdateformatter
我试图检测时间格式是12小时/ 24小时格式.基于此我在日历中设定时间.
我使用以下代码在viewDidLoad方法中检测设备上的24小时格式.
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]];
is24h = (amRange.location == NSNotFound && pmRange.location == NSNotFound);
Run Code Online (Sandbox Code Playgroud)
之后,我检查如下
if (is24h == TRUE) {
} else {
}
Run Code Online (Sandbox Code Playgroud)
但我总是得到is24h值是假的.如果设备设置为12小时格式,我可以在日历中设置时间.但如果是24小时格式,我无法设定时间.
你能告诉我我需要改变的地方吗?
使用此方法确定时间格式
- (BOOL)timeIs12HourFormat {
NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
NSRange containsA = [formatStringForHours rangeOfString:@"a"];
BOOL hasAMPM = containsA.location != NSNotFound;
return hasAMPM;
}
Run Code Online (Sandbox Code Playgroud)
根据unicode日期格式指南 j手段
这是一个特殊用途的符号.它不得出现在模式或骨架数据中.相反,它保留用于传递给执行灵活日期模式生成的API的骨架.在这样的上下文中,它请求区域设置(h,H,K或k)的首选小时格式,这由h,H,K或k是否以区域设置的标准短时间格式使用来确定.在这种API的实现中,在开始与availableFormats数据匹配之前,'j'必须被h,H,K或k替换.请注意,在传递给API的框架中使用"j"是使框架请求区域设置的首选时间周期类型(12小时或24小时)的唯一方法.
编辑
这将首先从设备的currentLocale获取formatString,然后它将检查"a"是否存在然后它是12小时格式,如果不是那么它是24小时格式.
| 归档时间: |
|
| 查看次数: |
2066 次 |
| 最近记录: |