How can I determine if iPhone is set for 12 hour or 24 hour time display?

后端 未结 5 1112
陌清茗
陌清茗 2020-12-01 04:13

I thought I saw something answering this on SO recently but now I can\'t find it. Here is the code I am using now to determine if settings are for 24 hour time display. It

5条回答
  •  清歌不尽
    2020-12-01 04:42

    I gave Dave's answer a shot, but when testing with German locale - a region where 24 hour time cycle is used - I realized it would be better to check for H or k in the format string instead of a, and that quoted substrings should be ignored.

    For German locale I get back "HH a" when requesting the date format for template "j" in the iOS simulator, and "HH 'Uhr'" on the device. (Do not understand why there is a difference at all.)

    Here is a category for NSLocale that I use to check for 24 hour time cycle:

    @interface NSLocale (TwentyFourHourTimeCycleCheck)
    
    - (BOOL)uses24HourTimeCycle;
    
    @end
    
    @implementation NSLocale (TwentyFourHourTimeCycleCheck)
    
    - (BOOL)uses24HourTimeCycle
    {
        BOOL uses24HourTimeCycle = NO;
    
        NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:self];
        NSScanner *symbolScanner = [NSScanner scannerWithString:formatStringForHours];
    
        NSString *singleQuoteCharacterString = @"'";
    
        // look for single quote characters, ignore those and the enclosed strings
        while ( ![symbolScanner isAtEnd] ) {
    
            NSString *scannedString = @"";
            [symbolScanner scanUpToString:singleQuoteCharacterString intoString:&scannedString];
    
            // if 'H' or 'k' is found the locale uses 24 hour time cycle, and we can stop scanning
            if ( [scannedString rangeOfString:@"H"].location != NSNotFound ||
                 [scannedString rangeOfString:@"k"].location != NSNotFound ) {
    
                uses24HourTimeCycle = YES;
    
                break;
            }
    
            // skip the single quote
            [symbolScanner scanString:singleQuoteCharacterString intoString:NULL];
            // skip everything up to and including the next single quote
            [symbolScanner scanUpToString:singleQuoteCharacterString intoString:NULL];
            [symbolScanner scanString:singleQuoteCharacterString intoString:NULL];
        }
    
        return uses24HourTimeCycle;
    }
    
    @end
    

提交回复
热议问题