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

旧城冷巷雨未停 提交于 2019-11-30 08:59:43

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

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.

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