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

我正在尝试获取下一个即将到来的星期五的日期,并将其格式设置为

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

回答:

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

以上是 如何将LocalDate格式化为yyyyMMDD(不使用JodaTime) 的全部内容, 来源链接: utcz.com/qa/436459.html

回到顶部