Java 8 LocalDate无法解析有效的日期字符串

时间:2018-09-20 18:10:57

标签: java datetime java-8 datetime-format localdate

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(...)调用中抛出。 解析器怎么了?!

2 个答案:

答案 0 :(得分:6)

来自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"here提到了Yy之间的区别。

答案 1 :(得分:0)

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

    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