Aro*_*hi 4 java java-time localdate datetimeformatter datetimeparseexception
我正在尝试将 a 转换String为LocalDateusing 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-31为31-Oct-2021.
我的代码做错了什么。
您的代码指定了模式dd-MMM-uuuu,但您尝试解析2021-10-31根本不适合此模式的文本。
您的字符串的正确模式是yyyy-MM-dd. 有关详细信息,请参阅格式化程序的文档。
特别是,观察日期和月份的顺序dd-MMM与MM-dd。及量月MMM。与您当前模式匹配的字符串将为31-Oct-2021.
来自评论:
我的输入日期是 - 2021-10-31 需要转换为 - 31-Oct-2021
您可以通过以下方式轻松更改日期模式:
yyyy-MM-dddd-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)
| 归档时间: |
|
| 查看次数: |
856 次 |
| 最近记录: |