将我的 Java 环境从 Java 11 (openjdk64-11.0.2) 升级到 Java 17 (oracle64-17.0.1),在 MacOS 上运行,我遇到了意外的日期格式解析错误。为了测试这一点,我编写了一个简短的 java 程序,然后在每个环境下编译并运行它。
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.UK);
for (String month : List.of("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")) {
String dateStr = "26 " + month + " 2021";
try {
LocalDate ld = LocalDate.parse(dateStr, formatter);
System.out.println(dateStr + " OK [" + ld.toString() + "]");
} catch (DateTimeParseException e) {
System.out.println(dateStr + " FAILED DateTimeParseException");
}
}
}
}
这是在两种环境下运行的输出:
~/work/jenv $jenv global openjdk64-11.0.2
~/work/jenv $java -version
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
~/work/jenv $javac Main.java
~/work/jenv $java Main
26 Jan 2021 OK [2021-01-26]
26 Feb 2021 OK [2021-02-26]
26 Mar 2021 OK [2021-03-26]
26 Apr 2021 OK [2021-04-26]
26 May 2021 OK [2021-05-26]
26 Jun 2021 OK [2021-06-26]
26 Jul 2021 OK [2021-07-26]
26 Aug 2021 OK [2021-08-26]
26 Sep 2021 OK [2021-09-26]
26 Oct 2021 OK [2021-10-26]
26 Nov 2021 OK [2021-11-26]
26 Dec 2021 OK [2021-12-26]
~/work/jenv $jenv global oracle64-17.0.1
~/work/jenv $java -version
java version "17.0.1" 2021-10-19 LTS
Java(TM) SE Runtime Environment (build 17.0.1+12-LTS-39)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.1+12-LTS-39, mixed mode, sharing)
~/work/jenv $javac Main.java
~/work/jenv $java Main
26 Jan 2021 OK [2021-01-26]
26 Feb 2021 OK [2021-02-26]
26 Mar 2021 OK [2021-03-26]
26 Apr 2021 OK [2021-04-26]
26 May 2021 OK [2021-05-26]
26 Jun 2021 OK [2021-06-26]
26 Jul 2021 OK [2021-07-26]
26 Aug 2021 OK [2021-08-26]
26 Sep 2021 FAILED DateTimeParseException
26 Oct 2021 OK [2021-10-26]
26 Nov 2021 OK [2021-11-26]
26 Dec 2021 OK [2021-12-26]
异常信息如下:
java.time.format.DateTimeParseException: Text '26 Sep 2021' could not be parsed at index 3
我很难相信 JDK 中存在错误,所以我错过了什么吗?提前致谢。