我是一名法国 Android 开发人员,因此使用Locale.getDefault()
会导致我DateFormat
使用 24 小时模式。但是,当我通过设置菜单手动将我的设备设置为 12 小时模式时,DateFormat
会继续以 24 小时格式运行。
相反,TimePicker
s是根据我自己的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());
}
}
在此之后,timeFormat
无论您的设备设置为以 24 小时格式还是 12 小时格式显示时间,都将正确格式化日期。并且TimePicker
也将正确设置。