Unexpected date result

I have a Java calendar viewer method that calculates the date for the year, day of the week, and week number.

Now that I am calculating dates from 2017, everything works. But when I calculate dates from January 2018, they take 2017 dates.

My code looks like

import java.time.temporal.IsoFields; import java.time.temporal.ChronoField; import java.time.LocalDate; // ..... LocalDate desiredDate = LocalDate.now() .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 1) .with(ChronoField.DAY_OF_WEEK, 1) .withYear(2018); 

What results will be obtained in 2018-01-02, and this should be 2018-01-01. How is this possible?

+8
java time localdate
source share
1 answer

The order of the methods being called seems substantial.
You call them in decreasing time-granularity (year, week of the week and day of the week), you get the correct result:

 long weekNumber = 1; long dayOfWeek = 1; int year = 2018; LocalDate desiredDate = LocalDate.now() .withYear(year) .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber) .with(ChronoField.DAY_OF_WEEK, dayOfWeek ); System.out.println(desiredDate); 

2018-01-01

Please note that the occurrence of the problem comes from:

 .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber) 

which sets the week number ( 1 to 53 ) according to the current year.
The Java LocalDate API cannot adapt this value if you change the year to .withYear(year) , because the week number information is not stored in the LocalDate instance.

You can really see in the LocalDate implementation that LocalDate instances LocalDate defined by only three fields: year , month and day .

 public final class LocalDate implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable { ... private final int year; /** * The month-of-year. */ private final short month; /** * The day-of-month. */ private final short day; ... } 

To be precise, it is important that:

.withYear(year) is called before

 .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber); 
+12
source share

All Articles