2011-02-27 77 views
9

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

在一个理想的世界,我想用NSDateFormatterShortStyle,但只是没有显示年份(仅一个月&日#)。什么是实现这一目标的最佳方式?

回答

18

您想使用NSDateFormatter的+ dateFormatFromTemplate:选项:区域:

下面是一些苹果的示例代码:

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 
+0

谢谢!这正是我所期待的。 – Jason 2011-02-27 23:18:55

4

大厦的示例代码,这里是一个一行,以确定当前locale是一天一(注:我放弃了“Y”为不引起我们的关注了这个问题。):

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

注意事项

dateFormatFromTemplate的文档声明“返回的字符串可能不完全包含模板中给出的那些组件,但可能 - 例如 - 应用了特定于区域的调整。”鉴于此,有时由于未知格式的原因,测试可能会返回FALSE(这意味着默认情况下,在默认情况下默认为月份优先)。自己决定使用哪种默认设置,或者是否需要增强测试以支持其他语言环境。

相关问题