12/24 小时模式冲突

Ric*_*nne 6 android simpledateformat android-timepicker

我是一名法国 Android 开发人员,因此使用Locale.getDefault()会导致我DateFormat使用 24 小时模式。但是,当我通过设置菜单DateFormat将设备手动设置为 12 小时模式时,会继续以 24 小时格式运行。

相反,TimePickers 是根据我自己的 12/24 小时设置来设置的。

有没有办法让DateFormats 的行为与 s 相同TimePicker

编辑:

这是我的DateFormat声明:

timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
Run Code Online (Sandbox Code Playgroud)

这是我将我设置TimePicker为 12 或 24 小时模式的地方。

tp.setIs24HourView(android.text.format.DateFormat.is24HourFormat((Context) this));
Run Code Online (Sandbox Code Playgroud)

我的解决方案:

根据下面@Meno Hochschild 的回答,这是我解决这个棘手问题的方法:

boolean is24hour = android.text.format.DateFormat.is24HourFormat((Context) this);
tp.setIs24HourView(is24hour); // tp is the TimePicker
timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
if (timeFormat instanceof SimpleDateFormat) {
    String pattern = ((SimpleDateFormat) timeFormat).toPattern();
    if (is24hour) {
        timeFormat = new SimpleDateFormat(pattern.replace("h", "H").replace(" a",""), Locale.getDefault());
    }
    else {
        timeFormat = new SimpleDateFormat(pattern.replace("H", "h"), Locale.getDefault());
    }
}
Run Code Online (Sandbox Code Playgroud)

在此之后,timeFormat无论您的设备设置为以 24 小时制还是 12 小时制显示时间,都将正确格式化日期。并且TimePicker也将被正确设置。

Men*_*ild 6

如果您指定了一个模式,SimpleDateFormat那么您已经固定了 12/24 小时模式,模式符号“h”(1-12)的情况下为 12 小时模式,模式符号“的情况下为 24 小时模式” H”(0-23)。备选方案“k”和“K”相似,但范围略有不同。

也就是说,指定模式使您的格式独立于设备设置!

另一种方法是使用DateFormat.getDateTimeInstance(),它使时间样式取决于系统区域设置(如果Locale.getDefault()可能会更改 - 或者您必须部署一种机制,如何询问当前设备区域设置,然后在 Android-Java 中进行设置Locale.setDefault())。

另一个特定于 Android 的想法是使用字符串常量TIME_12_24直接询问系统设置,然后指定依赖于此设置的模式。这似乎也可以通过特殊方法DateFormat.is24HourFormat()(请注意,Android 有两个不同的类 name DateFormat)。这种方法的具体例子:

boolean twentyFourHourStyle = 
  android.text.format.DateFormat.is24HourFormat((Context) this);
DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
if (df instanceof SimpleDateFormat) {
  String pattern = ((SimpleDateFormat) df).toPattern();
  if (twentyFourHourStyle) {
    df = new SimpleDateFormat(pattern.replace("h", "H"), Locale.getDefault());
  } else {
    df = new SimpleDateFormat(pattern.replace("H", "h"), Locale.getDefault());
  }
} else {
  // nothing to do or change
}
Run Code Online (Sandbox Code Playgroud)

您当然可以自由地针对可能出现的 k 和 K 来优化代码,或者注意文字 h 和 H 的使用(然后解析撇号以忽略替换方法中的这些部分)。