小编典典

如何将LocalDate格式化为yyyyMMDD(不使用JodaTime)

java

我正在尝试获取下一个即将到来的星期五的日期,并将其格式设置为
yyyyMMDD。如果可能,我想不使用JodaTime来执行此操作。这是
我的代码:

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;
import java.time.format.DateTimeFormatter;

// snippet from main method
LocalDate friday = LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern('yyyyMMDD');
System.out.println(friday.format(formatter));

But when I run this I get the following error (running it today 20170809)

java.time.DateTimeException: Field DayOfYear cannot be printed as the value 223 exceeds the maximum print width of 2

我究竟做错了什么?

编辑:我正在使用Java 8


阅读 12703

收藏
2020-11-23

共1个答案

小编典典

Big D means day-of-year. You have to use small d.

So in your case use "yyyyMMdd".

You can check all patterns
here.

This particular pattern is built into Java 8 and later:
DateTimeFormatter.BASIC_ISO_DATE

2020-11-23