NSDateFormatter time not changing according to phones settings

狂风中的少年 提交于 2019-12-08 08:24:46

问题


this one is killing me, I have the following date formatter:

+ (NSDateFormatter *)dateFormatter {
    static NSDateFormatter *_dateFormatter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *format = [NSDateFormatter dateFormatFromTemplate:@"hh:mm a" options:0 locale:[NSLocale currentLocale]];
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:format];
    });
    return _dateFormatter;
}   

I want the final hour format to be according to the user clock settings, so if the user uses "24-Hour Time", the result should be for example:

19:41

Otherwise the result should be

7:41 PM

ok now for the "killing me" part, this seems to work great if I set the phone's 'Region Format' to 'United States'.
If I toggle the "24-Hour Time" on/off the date indeed changes from 19:41 to 7:41 PM

BUT if I set the 'Region Format' to something different than 'United States', for example 'Spain' then I always get 7:41 pm no matter if I change the "24-Hour Time" on/off.

Even more weird is the fact that if I use the following template:

@"HH:mm a" (changed hh to uppercase HH)

Now 'Spain' works great and changes according to the "24-Hour Time" settings, BUT now the 'United State' is always in 24 hour format, no matter if I switch it off in settings!

whats going on here?!

Please consider that its important to me to use dateFormatFromTemplate and not regular format.


回答1:


Try this code

NSDate *time;
if ([objShare checkTimeFormat]){
    [timeFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];;
    [timeFormat setDateFormat:@"hh:mm a"];
    NSLog(@"%@",lblVtime.text);
    time = [timeFormat dateFromString:lblVtime.text];
}
else{
     NSLog(@"%@",lblVtime.text);
    [timeFormat setDateFormat:@"hh:mm a"];
    time = [timeFormat dateFromString:lblVtime.text];
}
[timeFormat setDateFormat:@"HH:mm"];
NSLog(@"%@",[timeFormat stringFromDate:time]);

Let me know if you have any query

The checkTimeFormat method:

-(BOOL)checkTimeFormat{
     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]];
     BOOL is24h = (amRange.location == NSNotFound && pmRange.location == NSNotFound);
     return is24h;
}


来源:https://stackoverflow.com/questions/22783110/nsdateformatter-time-not-changing-according-to-phones-settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!