我使用以下代码:
private long stampAsCal;
private DateFormat formatDateTime, formatDateTimeWSeconds, formatTimeOnly;
formatDateTime = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault());
formatDateTimeWSeconds = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.getDefault());
formatTimeOnly = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
和
return formatDateTimeWSeconds.format(stampAsCal);
我通常会得到一个像:
这样的字符串05.06.2018 22:00:48
但在某些情况下我会
05.06.2018 10:00:48 nachm.
代替
这里出了什么问题?
手机是Android 7.1.1的Moto Z Play
我的语言设置是德语(德国)。
我的日期时间设置为:
答案 0 :(得分:1)
不幸的是,该地区存在两个问题,其中大多数是described here。所有已知的版本都在较新的Android版本中修复,但在特定情况下这无济于事。
建议的解决方法是检查代码中的is24HourFormat
:
boolean use24Hour = android.text.format.DateFormat.is24HourFormat(context);
final String skeleton = use24Hour ? "Hm" : "hm";
final String pattern = android.text.format.DateFormat.getBestDateTimePattern(locale, skeleton);
DateFormat formatter = new SimpleDateFormat(pattern, locale);
根据需要调整骨架以获得所需的格式。
答案 1 :(得分:0)
首先,非常感谢Joachim Sauer发现问题并找到解决方案。
如果有人希望这也适用于API18之前的版本,那么我决定如何处理Android错误:
boolean use24Hour = android.text.format.DateFormat.is24HourFormat(MainActivity.getContext());
if (use24Hour && formatDateTimeWSeconds instanceof SimpleDateFormat) {
String pattern = ((SimpleDateFormat) formatDateTimeWSeconds).toPattern();
if (pattern.contains("h")) {
pattern = pattern.replace("hh", "HH").replace("h", "HH").replace(" a", "").replace("a", "");
formatDateTimeWSeconds = new SimpleDateFormat(pattern, Locale.getDefault());
}
}