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

zer*_*pha 4 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));
Run Code Online (Sandbox Code Playgroud)

但是当我运行此命令时,出现以下错误(今天运行20170809)

java.time.DateTimeException: Field DayOfYear cannot be printed as the value 223 exceeds the maximum print width of 2
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

编辑:我正在使用Java 8

Bye*_*Bye 5

D手段day-of-year。您必须使用小号d

所以在你的情况下使用"yyyyMMdd"

您可以在此处检查所有模式。

此特定模式内置于Java 8及更高版本中: DateTimeFormatter.BASIC_ISO_DATE


Tod*_*odd 5

我认为你有两个问题。

首先,您将字符串括在字符文字中 ( ''vs "")。

其次,DD格式字符串中的(一年中的某一天)必须是dd(一月中的某一天)。

DateTimeFormatter.ofPattern("yyyyMMdd");
Run Code Online (Sandbox Code Playgroud)