微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – 12/24小时模式冲突

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

相反,TimePickers根据我自己的12/24小时设置进行设置.

有没有办法让DateFormats的行为与TimePickers相同?

编辑:

这是我的DateFormat声明:

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

这里是我设置TimePickerto 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());
    }
}

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

解决方法

如果您在SimpleDateFormat中指定了一个模式,那么您已经修复了12/24小时模式,在模式符号“h”(1-12)的情况下为12小时模式,在模式符号的情况下为24小时模式“H”(0-23).替代“k”和“K”类似,范围略有不同.

也就是说,指定一个模式会使您的格式与设备设置无关!

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

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",Locale.getDefault());
  }
} else {
  // nothing to do or change
}

您当然可以自由地为可能出现的k和K细化代码,或者注意使用文字h和H(然后解析叛逆者在替换方法中忽略这些部分).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐