如何确定区域设置的日期格式是月/日还是日/月?

Jas*_*son 10 iphone nsdate internationalization nsdateformatter ios

在我的iPhone应用程序中,我希望能够确定用户的区域设置的日期格式是月/日(即1月5日的1/5)还是日/月(即1月5日的5/1).我有一个NSDateFormatter不使用其中一种基本格式的自定义,如NSDateFormatterShortStyle(11/23/37).

在理想的世界中,我想使用NSDateFormatterShortStyle,但只是不显示年份(只有月份和日期#).实现这一目标的最佳方法是什么?

sbo*_*oth 18

您想使用NSDateFormatter的+ dateFormatFromTemplate:options:locale:

这是一些Apple示例代码:

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
Run Code Online (Sandbox Code Playgroud)


Wil*_*iss 6

在示例代码的基础上,这是一个单行程序,用于确定当前区域设置是否为第一天(nb.我删除了'y',因为这与我们的问题无关):

BOOL dayFirst = [[NSDateFormatter dateFormatFromTemplate:@"MMMMd" options:0 locale:[NSLocale currentLocale]] hasPrefix:@"d"];
Run Code Online (Sandbox Code Playgroud)

NB.dateFormatFromTemplate状态的文档"返回的字符串可能不包含模板中给出的那些组件,但可能 - 例如 - 应用了特定于语言环境的调整." 鉴于此,有时测试可能由于未知格式而返回FALSE(意味着它在默认情况下默认为月份优先).确定您喜欢哪个默认值,或者您是否需要增强测试以支持其他语言环境.