Java 8 LocalDate 不会解析有效的日期字符串

Java 8 LocalDate won't parse valid date string

Java 8 在这里。我有以下代码:

final String createdDateStr = "20110920";
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYYMMdd");
final LocalDate localDate = LocalDate.parse(createdDateStr, formatter);

在运行时我得到以下异常:

java.time.format.DateTimeParseException: Text '20110920' could not be parsed at index 0

    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.

...从 LocalDate.parse(...) 调用中抛出。 解析器出了什么问题?!

来自 the documentation 的示例:

LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);

您应该使用 "yyyyMMdd" 而不是 "YYYYMMdd"Yy 之间的区别提到了 here

无需手动指定格式。已经内置了。

    final String createdDateStr = "20110920";
    final DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
    final LocalDate localDate = LocalDate.parse(createdDateStr, formatter);
    System.out.println(localDate);

这输出:

2011-09-20