【问题标题】:How would I get a locale-based short date string for Android?如何为 Android 获取基于语言环境的短日期字符串?
【发布时间】:2014-06-18 03:44:37
【问题描述】:

我正在尝试获取一个日期字符串,除了月份之外,还包含星期几和月份的缩短形式。

例如,使用英语语言环境的用户会看到:

6 月 17 日星期二

使用德语区域设置的用户会看到:

迪。 6 月 17 日

我一直在查看 android.text.format.DateFormat 文档,getBestDateTimePattern(Locale locale, String skeleton) 看起来可能有效,但它需要 API 18+,所以我不能使用它。

有没有办法获得这种基于用户当前语言环境的短格式?

【问题讨论】:

    标签: android date localization


    【解决方案1】:

    好吧,我想我终于想通了:

    int flags = DateUtils.FORMAT_SHOW_DATE | 
                DateUtils.FORMAT_NO_YEAR | 
                DateUtils.FORMAT_ABBREV_ALL | 
                DateUtils.FORMAT_SHOW_WEEKDAY;
    
    dateTextView.setText(DateUtils.formatDateTime(this, millis, flags));
    

    对于英语语言环境,您会得到:

    6 月 18 日,星期三

    对于德语语言环境,您会得到:

    密歇根州,18. 朱尼

    对于法语语言环境,您会得到:

    mer。 6月18日

    【讨论】:

      【解决方案2】:

      您应该使用getMeduimDateFormat(Context),这符合当前的语言环境和用户的偏好。

      【讨论】:

      • 感谢您的帮助。它很接近,但不完全是我想要的。
      【解决方案3】:

      试试下面的代码:-

      public class DateFormatDemoSO {
        public static void main(String args[]) {
          int style = DateFormat.MEDIUM;
          //Also try with style = DateFormat.FULL and DateFormat.SHORT
          Date date = new Date();
          DateFormat df;
          df = DateFormat.getDateInstance(style, Locale.UK);
          System.out.println("United Kingdom: " + df.format(date));
          df = DateFormat.getDateInstance(style, Locale.US);
          System.out.println("USA: " + df.format(date));   
          df = DateFormat.getDateInstance(style, Locale.FRANCE);
          System.out.println("France: " + df.format(date));
          df = DateFormat.getDateInstance(style, Locale.ITALY);
          System.out.println("Italy: " + df.format(date));
          df = DateFormat.getDateInstance(style, Locale.JAPAN);
          System.out.println("Japan: " + df.format(date));
        }
      }
      

      欲了解更多信息,请参阅以下链接:-

      http://www.java2s.com/Code/Java/Data-Type/DateFormatwithLocale.htm

      【讨论】:

      • 感谢您的回复。然而,那些日期字符串太长了。
      【解决方案4】:

      乔达时间

      使用Joda-Time 库。

      DateTimeFormatter formatter = DateTimeFormat.forStyle( "S-" ).withLocale( java.util.Locale.getDefault() ); // "S" for short date format. "-" to suppress the time portion. Specify locale for cultural rules about how to format a String representation.
      DateTime dateTime = new DateTime( someDateObject, DateTimeZone.getDefault() ); // Convert a java.util.Date object to an org.joda.time.DateTime object. Specify time zone to assign to DateTime.
      String output = formatter.print( dateTime ); // Generate String representation of date-time value.
      

      【讨论】:

      • 您好罗勒感谢您的回答。我确实需要调查 Joda Time,因为我一直听到很多关于它的消息,但现在我已经解决了我发布的答案中的问题。
      猜你喜欢
      • 2011-11-03
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 2012-03-17
      • 2012-04-14
      • 1970-01-01
      • 2015-01-21
      相关资源
      最近更新 更多