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

在我的iPhone应用程序中,我希望能够确定用户的语言环境的date格式是月/日(即1月5日的1/5)还是日/月(即1月5日的5/1)。 我有一个自定义的NSDateFormatter不使用NSDateFormatterShortStyle (11/23/37)等基本格式之一。

在一个理想的世界中,我想使用NSDateFormatterShortStyle,但不显示年份(只有月份和date#)。 什么是完成这个最好的方法?

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

以下是一些苹果示例代码:

 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 

在示例代码的基础上,下面是一个确定当前语言环境是否为“白天优先”的单行语句(即,我放弃了'y',因为这个问题与我们无关):

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

NB。 dateFormatFromTemplate的文档声明:“返回的string可能并不完全包含模板中给出的那些组件,但例如可能会应用特定于区域的调整”。 鉴于此,有时由于未知格式的原因,testing可能会返回FALSE(这意味着在不清楚时默认为月份优先)。 自己决定使用哪个默认值,或者是否需要增强testing以支持更多的区域设置。