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; private final short 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);
davidxxx
source share