考虑以下日期:
String date = "2391995";
String patt = "ddMyyyy";
使用提供的模式,我们可以看到
date
代表 1995 年 9 月 23 日。
但是考虑一下尝试解析它时会发生什么 - 首先是旧方法,然后是 Java 8+ 方法:
Date dd = new SimpleDateFormat(patt).parse(date);
System.out.println(dd);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(patt);
LocalDate d = LocalDate.parse(date, formatter);
System.out.println(d);
输出:
Sat Sep 23 00:00:00 EDT 1995
Exception in thread "main" java.time.format.DateTimeParseException: Text '2391995' could not be parsed at index 7
...
正如我们所见,使用
SimpleDateFormat
的旧方法可以按预期工作。但是当使用DateTimeFormatter
和LocalDate.parse
时,就会出现错误。这是为什么?