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
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.
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.
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
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With