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

亡梦爱人 提交于 2019-11-29 12:55:55

问题


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.



来源:https://stackoverflow.com/questions/5135482/how-to-determine-if-locales-date-format-is-month-day-or-day-month

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