【问题标题】:How to detect the system time format change in ios?如何检测ios中的系统时间格式变化?
【发布时间】:2014-11-26 09:16:44
【问题描述】:

我想检测系统设置中的时间格式更改。我使用了以下代码,但它总是给我旧格式。如何获得新的时间格式?

#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);
}

【问题讨论】:

    标签: ios objective-c nsdate nsdateformatter nslocale


    【解决方案1】:

    我不知道您为什么希望 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];
    

    【讨论】:

    • 首先感谢您在我的应用程序中回答我的观点是随着时间格式的变化而变化,所以我想检测系统时间格式的变化。
    • 非常感谢您的回答,它工作正常。我想为此投票,但我没有足够的观点。非常感谢。
    【解决方案2】:

    存储系统时间格式。将其存储在 NSUserDefaults 中说 PtimeFormat 下次启动应用程序时检查 PtimeFormat 是否存在。再次获取系统的时间格式并匹配两种格式,无论它们是否相同。

    【讨论】:

    • 但它总是给旧的时间甲酸盐而不是新的甲酸盐。因此,当我再次启动应用程序时,它会为我提供我们保存在 NSUserDefaults 中的相同时间格式。感谢您的回答
    • 好的,我没试过。做一件事,在更改时间格式后重新启动您的设备,然后启动您的应用程序是否会发生任何变化?
    • 是的,在我的应用程序中,我的观点是随着时间甲酸盐的变化而变化,所以这是不可能的。
    猜你喜欢
    • 2011-01-16
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多