【问题标题】:Localizing dates in android在android中本地化日期
【发布时间】:2015-06-14 00:13:36
【问题描述】:

在阅读了接受德语的Date formatting based on user locale on android 的答案后,我测试了以下内容:

@Override
protected void onResume() {
    super.onResume();
    String dateOfBirth = "02/26/1974";
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    Date date = null;
    try {
        date = sdf.parse(dateOfBirth);
    } catch (ParseException e) {
        // handle exception here !
    }
    // get localized date formats
    DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
    String s = dateFormat.format(date);
    dateTV.setText(s);
}

这里的 dateOfBirth 是一个英文日期。但是,如果我将手机的语言更改为德语,我会看到 02.26.1974。根据http://en.wikipedia.org/wiki/Date_format_by_country,正确的本地化德语日期格式是dd.mm.yyyy,所以我希望看到“26.02.1974”。

这引出了我的问题,有没有办法完全本地化日期,或者这是一个手动过程,我必须在我的应用程序中仔细查看日期、时间等?

【问题讨论】:

  • 但是您自己在new SimpleDateFormat("MM/dd/yyyy"); 中定义了一种格式,格式化日期结果的唯一区别是使用点而不是斜线。此外,您没有在代码中的任何地方使用 Locale。
  • @Stan getDateFormat 返回本地化格式:developer.android.com/reference/android/text/format/…。我正在尝试找到可以“完全”本地化的代码,重新排列数字,而不仅仅是在这种情况下用点替换。

标签: android date localization


【解决方案1】:
    String dateOfBirth = "02/26/1974";
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    Date date = null;
    try {
        date = sdf.parse(dateOfBirth);
    } catch (Exception e) {
        // handle exception here !
    }
    // get localized date formats
    Log.i(this,"sdf default: "+new SimpleDateFormat().format(date)); // using my phone locale
    DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.US);
    Log.i(this,"dateFormat US DEFAULT: "+dateFormat.format(date));
    dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.GERMAN);
    Log.i(this,"dateFormat GERMAN DEFAULT: "+dateFormat.format(date));
    dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.CHINESE);
    Log.i(this,"dateFormat CHINESE DEFAULT: "+dateFormat.format(date));
    dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
    Log.i(this,"dateFormat US SHORT: "+dateFormat.format(date));
    dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN);
    Log.i(this,"dateFormat GERMAN SHORT: "+dateFormat.format(date));
    dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.CHINESE);
    Log.i(this,"dateFormat CHINESE SHORT: "+dateFormat.format(date));

输出是:

 sdf default: 26.02.74 0:00
 dateFormat US DEFAULT: Feb 26, 1974
 dateFormat GERMAN DEFAULT: 26.02.1974
 dateFormat CHINESE DEFAULT: 1974-2-26
 dateFormat US SHORT: 2/26/74
 dateFormat GERMAN SHORT: 26.02.74
 dateFormat CHINESE SHORT: 74-2-26

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-08
    • 2021-12-13
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多