gpt4 book ai didi

android - 12/24 小时模式冲突

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:48:19 26 4
gpt4 key购买 nike

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

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

有什么方法可以使 DateFormat 的行为与 TimePicker 的行为相同?

编辑:

这是我的 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 也将被正确设置。

最佳答案

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

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

另一种方法是使用 DateFormat.getDateTimeInstance()这使得时间样式依赖于系统区域设置(如果 Locale.getDefault() 可能会改变 - 或者你必须部署一种机制如何询问当前设备区域设置,然后在 Android-Java 中设置 Locale.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 的使用(然后解析撇号以在 replace-method 中忽略这些部分)。

关于android - 12/24 小时模式冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23222199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com