How to determine if locale's date format is Mo

2019-02-06 15:16发布

问题:

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). I have a custom NSDateFormatter which does not use one of the basic formats such as NSDateFormatterShortStyle (11/23/37).

In an ideal world, I want to use NSDateFormatterShortStyle, but just not display the year (only month & day#). What's the best way to accomplish this?

回答1:

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


回答2:

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.