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

标签 ios objective-c nsdate nsdateformatter 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);
}

最佳答案

我不确定如果日期发生显着变化,您为什么期望 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/

相关文章:

ios - 使用未解析的标识符 'image'

ios - UI 处理导致音频故障 - 音频应该在后台线程上播放吗?

iphone - 如何解析Json对象

ios - 如何在所有时区/地区向 NSCalendar 添加天数

objective-c - 在 NSUserDefaults 中存储日期抛出异常

ios - 查找两个时间戳之间的差异 - iOS

ios - 下拉刷新时 UITableview 出错,所有数据重复出现。任何人都可以帮助使用 Swift3 , Xcode8

iphone - 当目标对象已经为 NULL 时,iOS 如何捕获发送到实例的无法识别的选择器异常?

ios - Objective c 拆分字符串问题

iphone - 更改 IBOutletCollection 的帧值