12/24小时模式冲突 [英] 12/24-hour mode conflict

查看:0
本文介绍了12/24小时模式冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

是否有方法使DateFormat%s的行为方式与TimePicker%s相同?

编辑:

这是我的DateFormat声明:

timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());

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

tp.setIs24HourView(android.text.format.DateFormat.is24HourFormat((Context) this));

我的解决方案:

根据@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());
    }
}
之后,无论您的设备设置为以24小时制还是12小时制显示时间,timeFormat都将正确设置日期格式。TimePicker也将正确设置。

推荐答案

如果您在SimpleDateFormat中指定了模式,则您已经固定了12/24小时模式,如果是模式符号"h"(1-12),则是12小时模式;如果是模式符号"H"(0-23),则是24小时模式。备选"k"和"k"相似,但范围略有不同。

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

另一种方法是使用DateFormat.getDateTimeInstance(),这会使时间样式依赖于系统区域设置(如果Locale.getDefault()可能会发生变化,或者您必须部署一种机制来询问当前设备的区域设置,然后在Android-JavaLocale.setDefault()中进行设置)。

Android特有的另一个想法是使用字符串常量TIME_12_24直接询问系统设置,然后指定依赖于此设置的模式。这似乎也可以通过特殊的方法DateFormat.is24HourFormat()(请注意,Android有两个不同的类,名称为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
}

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

这篇关于12/24小时模式冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆