Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format LocalDate to yyyyMMDD (without JodaTime)

Tags:

java

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

like image 528
secondbreakfast Avatar asked Aug 09 '17 18:08

secondbreakfast


People also ask

How do I get strings from LocalDate?

The toString() method of a LocalDate class is used to get this date as a String, such as 2019-01-01. The output will be in the ISO-8601 format uuuu-MM-dd. Parameters: This method does not accepts any parameters. Return value: This method returns String which is the representation of this date, not null.

Can we convert LocalDate to date in Java?

Convert LocalDate To Date in Java Step 1: First Create the LocalDate object using either now() or of() method. now() method gets the current date where as of() creates the LocalDate object with the given year, month and day. Step 2: Next, Get the timezone from operating system using ZoneId. systemDefault() method.


2 Answers

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

like image 162
ByeBye Avatar answered Oct 19 '22 06:10

ByeBye


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");
like image 32
Todd Avatar answered Oct 19 '22 07:10

Todd