我正在尝试格式化日期,格式如下:05051988
。我想使用LocalDate
在下一个 05 May 1988
进行格式化。
我创建了私有(private)方法,稍后我将在同一类中使用该方法在文本中输入格式化日期。我已经编写了一些代码,但目前如果我使用 MM
,如果我将其替换为 MMM
,我会得到 1988-05-05
code> 然后它给我无法解析的错误消息。
private LocalDate parseDate(){
LocalDate dateOfBirth = LocalDate.parse(date, DateTimeFormatter.ofPattern("ddMMyyyy"));
return dateOfBirth;
}
错误:
Exception in thread "main" java.time.format.DateTimeParseException: Text '05051988' could not be parsed at index 2
最佳答案
您仍然需要使用“ddMMyyyy”来解析日期。然后打印时用“dd MMM yyyy”格式化。
类似这样的事情:
String reformat(String dateOfBirth) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd MMM yyyy");
LocalDate date = LocalDate.parse(dateOfBirth, fomatter);
return formatter2.print(date);
}
关于java - 在 java.time 中格式化日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25193686/