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

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

本文介绍了Java 8 LocalDate不会解析有效的日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 8。我有以下代码:

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.

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

推荐答案

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

您应该使用yyyyMMdd而不是 年月日。提到 Y y 之间的差异。

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

这篇关于Java 8 LocalDate不会解析有效的日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:48