How to determine if locale's date format is Month/Day or Day/Month?

前端 未结 2 1075
离开以前
离开以前 2020-12-31 08:08

In my iPhone app, I\'d like to be able to determine if the user\'s locale\'s date format is Month/Day (i.e. 1/5 for January fifth) or Day/Month (i.e. 5/1 for January fifth).

相关标签:
2条回答
  • 2020-12-31 08:50

    You want to use NSDateFormatter's +dateFormatFromTemplate:options:locale:

    Here is some Apple sample code:

    NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
    
    NSString *dateFormat;
    NSString *dateComponents = @"yMMMMd";
    
    dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:usLocale];
    NSLog(@"Date format for %@: %@",
        [usLocale displayNameForKey:NSLocaleIdentifier value:[usLocale localeIdentifier]], dateFormat);
    
    dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:gbLocale];
    NSLog(@"Date format for %@: %@",
        [gbLocale displayNameForKey:NSLocaleIdentifier value:[gbLocale localeIdentifier]], dateFormat);
    
    // Output:
    // Date format for English (United States): MMMM d, y
    // Date format for English (United Kingdom): d MMMM y
    
    0 讨论(0)
  • 2020-12-31 09:00

    Building on the sample code, here's a one-liner to determine if the current locale is day-first (nb. I dropped the 'y' as that doesn't concern us for this question):

    BOOL dayFirst = [[NSDateFormatter dateFormatFromTemplate:@"MMMMd" options:0 locale:[NSLocale currentLocale]] hasPrefix:@"d"];
    

    NB. The docs for dateFormatFromTemplate state that "The returned string may not contain exactly those components given in template, but may—for example—have locale-specific adjustments applied." given this, sometimes the test may return FALSE due to an unknown format (meaning it defaults to month-first when unclear). Decide for yourself which default you prefer, or if you need to enhance the test to support additional locales.

    0 讨论(0)
提交回复
热议问题