【问题标题】:How to determine if locale's date format is Month/Day or Day/Month?如何确定语言环境的日期格式是月/日还是日/月?
【发布时间】:2011-07-05 08:42:46
【问题描述】:

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

在理想情况下,我想使用 NSDateFormatterShortStyle,但不显示年份(仅显示月份和日期#)。完成此任务的最佳方法是什么?

【问题讨论】:

    标签: iphone ios internationalization nsdate nsdateformatter


    【解决方案1】:

    在示例代码的基础上,这里有一个单行代码来确定当前的语言环境是否是第一天(注意,我删除了“y”,因为我们不关心这个问题):

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

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

    【讨论】:

      【解决方案2】:

      你想使用 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
      

      【讨论】:

      • 谢谢!这正是我想要的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      相关资源
      最近更新 更多