我想检测在系统设置中完成的时间格式更改。我使用了以下代码,但它总是给我旧格式。我怎样才能得到新的时间格式?
#pragma mark
#pragma mark - application change time format
-(void)applicationSignificantTimeChange:(UIApplication *)application
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateStyle:NSDateFormatterNoStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSLog(@"dataString ::%@",dateString);
NSRange amRange = [dateString rangeOfString:[formatter AMSymbol]];
NSRange pmRange = [dateString rangeOfString:[formatter PMSymbol]];
is12Hour = (amRange.length > 0 || pmRange.length > 0);
}
最佳答案
我不确定如果日期发生显着变化,您为什么期望 dateFormat 发生变化。
当时间(即 [NSDate date]
)改变时触发显着时间改变事件。例如,如果新的一天开始,如果用户更改时区或者夏令时开始或结束。
但这些事件不会改变日期格式。
我想你想监控语言环境的变化。有一个通知:NSCurrentLocaleDidChangeNotification
。
像这样的东西应该可以工作:
j
是一个模板,将由日期模板替换为 h a
(12 小时格式)或 H
(24 小时格式)方法
id localeDidChangeNotification = [[NSNotificationCenter defaultCenter] addObserverForName:NSCurrentLocaleDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
if ([dateFormat rangeOfString:@"h"].location != NSNotFound) {
// 12 hour
}
else {
// 24 hour
}
}];
// Don't forget to remove the notification in the appropriate place
// [[NSNotificationCenter defaultCenter] removeObserver:localeDidChangeNotification];
关于ios - 如何检测ios中的系统时间格式变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27145240/