如何检测ios中的系统时间格式变化?

chi*_*hah 0 objective-c nsdate nsdateformatter ios nslocale

我想检测系统设置中完成的时间格式更改.我使用下面的代码,但它总是给我时间旧的格式.我怎样才能获得新的时间格式?

#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);
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*uch 5

我不确定为什么你期望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];
Run Code Online (Sandbox Code Playgroud)