【问题标题】:Android bug: DateFormat() sometimes shows 12hr format, when it should show 24hr formatAndroid 错误:DateFormat() 有时显示 12 小时格式,而它应该显示 24 小时格式
【发布时间】:2018-11-15 20:37:03
【问题描述】:

我使用以下代码:

private long stampAsCal;
private DateFormat formatDateTime, formatDateTimeWSeconds, formatTimeOnly;
formatDateTime = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault());
formatDateTimeWSeconds = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.getDefault());
formatTimeOnly = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());

    return formatDateTimeWSeconds.format(stampAsCal);

我通常会得到这样的字符串:

05.06.2018 22:00:48

但在某些情况下我会得到

05.06.2018 10:00:48 nachm.

改为

这里出了什么问题?


手机是装有 Android 7.1.1 的 Moto Z Play

我的语言设置是德语(德国)。

我的日期时间设置是:

  • 自动日期/时间(网络)
  • 自动时区(网络)
  • 24 小时制有效

【问题讨论】:

    标签: java android time format


    【解决方案1】:

    不幸的是,该区域有几个问题,其中大部分是described here。所有已知的问题都在较新的 Android 版本中得到修复,但在特定情况下这并没有足够的帮助。

    一个建议的解决方法是在您的代码中检查is24HourFormat

    boolean use24Hour = android.text.format.DateFormat.is24HourFormat(context); 
    final String skeleton = use24Hour ? "Hm" : "hm"; 
    final String pattern = android.text.format.DateFormat.getBestDateTimePattern(locale, skeleton);
    DateFormat formatter = new SimpleDateFormat(pattern, locale); 
    

    根据需要调整骨架以获得所需的格式。

    【讨论】:

    • 这似乎是我的问题背后的确切根本原因。但是,由于 .getBestDateTimePattern() 是随 API18 引入的,并且我使用 API 15 以上,我需要进一步研究我的选项。但是非常感谢到目前为止的提示,我会报告回来
    【解决方案2】:

    首先,非常感谢 Joachim Sauer 发现问题并找到了解决方案。


    如果有人希望这也适用于 API18 之前的版本,我决定如何处理 Android 错误:

        boolean use24Hour = android.text.format.DateFormat.is24HourFormat(MainActivity.getContext());
        if (use24Hour && formatDateTimeWSeconds instanceof SimpleDateFormat) {
             String pattern = ((SimpleDateFormat) formatDateTimeWSeconds).toPattern();
            if (pattern.contains("h")) {
                pattern = pattern.replace("hh", "HH").replace("h", "HH").replace(" a", "").replace("a", "");
                formatDateTimeWSeconds = new SimpleDateFormat(pattern, Locale.getDefault());
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 2022-08-08
      • 2023-03-20
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多