secondbreakfast
secondbreakfast

Reputation: 4384

How to format LocalDate to yyyyMMDD (without JodaTime)

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

Upvotes: 14

Views: 40790

Answers (2)

ByeBye
ByeBye

Reputation: 6946

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

Upvotes: 19

Todd
Todd

Reputation: 31710

I think you have two problems.

First, you are enclosing a String in character literals ('' vs "").

Second, the DD (day of year) in your format string needs to be dd (day of month).

DateTimeFormatter.ofPattern("yyyyMMdd");

Upvotes: 5

Related Questions