gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:07:32 24 4
gpt4 key购买 nike

这里是 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 .

关于Java 8 LocalDate 不会解析有效的日期字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52430930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com