[英]DateTimeFormatter in Java 11 (Zulu) does not work for formats with AM / PM
I am trying to convert a String representing a time in AM/PM format to java.sql.Time, but I get a DateTimeParseException:我正在尝试将表示 AM/PM 格式的时间的 String 转换为 java.sql.Time,但我收到 DateTimeParseException:
public static java.sql.Time getTimeValue(String valStr) {
if (valStr == null || valStr.isEmpty()) {
return null;
}
DateTimeFormatter dateTimeFormatter;
if (valStr.toUpperCase().endsWith("AM") || valStr.toUpperCase().endsWith("PM")) {
dateTimeFormatter = DateTimeFormatter.ofPattern("h:mm a");
} else {
dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm");
}
try {
return java.sql.Time.valueOf(LocalTime.parse(valStr, dateTimeFormatter));
} catch (Exception ex) {
return null;
}
}
For an input value of "7:16 PM" I get the following exception:对于“7:16 PM”的输入值,我得到以下异常:
java.time.format.DateTimeParseException: Text '7:16 PM' could not be parsed at index 5
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
at java.base/java.time.LocalTime.parse(LocalTime.java:463)
at ...getTimeValue(....java:864)
I am using Java 11.0.5, Zulu 11.35.15 for 64-bits.我使用的是 Java 11.0.5,64 位的 Zulu 11.35.15。
Does anyone have any idea on why this isn't working?有没有人知道为什么这不起作用? I have no problems with the same piece of code in Java 8.
我对 Java 8 中的同一段代码没有任何问题。
I have checked the value of the DateTimeFormatter and it is the one corresponding to the "h:mm a" pattern.我检查了 DateTimeFormatter 的值,它是对应于“h:mm a”模式的值。
Thanks a lot John Skeet and Robert, indeed, it was a Locale problem.非常感谢 John Skeet 和 Robert,确实,这是一个语言环境问题。
The solution was to always create the DateTimeFormatter with the Locale.US argument, so everything works as expected now.解决方案是始终使用 Locale.US 参数创建 DateTimeFormatter,因此现在一切都按预期工作。
if (valStr.toUpperCase().endsWith("AM") || valStr.toUpperCase().endsWith("PM")) {
dateTimeFormatter = DateTimeFormatter.ofPattern("h:mm a", Locale.US);
} else {
dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.