解析 LocalDate 但得到 DateTimeParseException;dd-MMM-uuuu

Aro*_*hi 4 java java-time localdate datetimeformatter datetimeparseexception

我正在尝试将 a 转换StringLocalDateusing DateTimeFormatter,但收到异常:

java.time.format.DateTimeParseException:无法在索引 5 处解析文本“ 2021-10-31 ”

我的代码是

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-uuuu");
String text = "2021-10-31";
LocalDate date = LocalDate.parse(text, formatter);
Run Code Online (Sandbox Code Playgroud)

我正在尝试从输入日期转换2021-10-3131-Oct-2021.

Zab*_*uza 6

怎么了?

我的代码做错了什么。

您的代码指定了模式dd-MMM-uuuu,但您尝试解析2021-10-31根本不适合此模式的文本。

您的字符串的正确模式是yyyy-MM-dd. 有关详细信息,请参阅格式化程序的文档。

特别是,观察日期和月份的顺序dd-MMMMM-dd。及量月MMM。与您当前模式匹配的字符串将为31-Oct-2021.


改变模式

来自评论:

我的输入日期是 - 2021-10-31 需要转换为 - 31-Oct-2021

您可以通过以下方式轻松更改日期模式:

  1. 使用模式解析输入日期yyyy-MM-dd
  2. 然后使用模式将其格式化回字符串dd-MMM-yyyy

用代码来说,就是:

DateTimeFormatter inputPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
DateTimeFormatter outputPattern = DateTimeFormatter.ofPattern("dd-MMM-yyyy");

String input = "2021-10-31";
LocalDate date = LocalDate.parse(text, inputPattern);

String output = date.format(outputPattern);
Run Code Online (Sandbox Code Playgroud)