How to format LocalDate to yyyyMMDD (without JodaTime)

zero01alpha :

I am trying to get the date of the the next upcoming Friday and format it as yyyyMMDD. I would like to do this without using JodaTime if possible. Here is my code:

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

What am I doing wrong?

edit: I am using Java 8

ByeBye :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=472993&siteId=1