Java 8 LocalDate won't parse valid date string [duplicate]

ε祈祈猫儿з 提交于 2019-12-01 06:33:25

问题


Java 8 here. I have the following code:

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

At runtime I get the following exception:

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.

...being thrown from the LocalDate.parse(...) invocation. What is wrong with the parser?!


回答1:


An example from the documentation:

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

You should use "yyyyMMdd" instead of "YYYYMMdd". The difference between Y and y was mentioned here.




回答2:


No need to specify the format by hand. It’s already built-in.

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

This outputs:

2011-09-20



来源:https://stackoverflow.com/questions/52430930/java-8-localdate-wont-parse-valid-date-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!