我正以这种格式传递日期-“ JAN01 / 2020”,但似乎找不到它的DateTimeFormatter模式。我尝试了这些(以及其他几个),但是它们导致DateTimeParseException-
DateTimeFormatter.ofPattern("MMMd/YYYY").parse("JAN01/2020")
DateTimeFormatter.ofPattern("MMMdd/YYYY").parse("JAN01/2020")
我也考虑了这篇文章的解决方案,下面的三行也导致DateTimeParseException。它似乎不是区分大小写的问题Java 8 DateTimeFormatter for month in all CAPS not working
DateTimeFormatter formatter= DateTimeFormatter.ofPattern("MMMdd/yyyy");
LocalDateTime dateTime = LocalDateTime.parse("JAN14/2020", formatter);
System.out.println(dateTime.getYear());
我感谢任何建议!
格式的主要问题是,您使用的是YYYY
而不是yyyy
。如下进行:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
class Main {
public static void main(String args[]) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("MMMd/yyyy")
.toFormatter();
System.out.println(LocalDate.parse("JAN01/2020", formatter));
}
}
输出:
2020-01-01
使用DateTimeFormatterBuilder
处理案件>
.parseCaseInsensitive()
的情况.appendPattern("MMMdd/yyyy")
用于模式解析为LocalDate
,因为没有时间成分
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("MMMdd/yyyy");
DateTimeFormatter dateFormat = builder.toFormatter();
LocalDate dateTime = LocalDate.parse("JAN14/2020", dateFormat);
System.out.println(dateTime); // 2020-01-14