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(然后解析叛逆者在替换方法中忽略这些部分).

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...