I have a method to view a calendar in Java that calculates the date by year, day of the week and week-number.
Now when I calculates the dates from 2017 everything works. But when I calculates the dates from January 2018 it takes the dates of year 2017.
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);
Which results in 2018-01-02 and it should be 2018-01-01. How is this possible?
I want to mention, that there is another Problem(?) with LocalDate.
This Code does also create a wrong result:
If you change the creation of the
year
variable tothe code returns the expected result. It seems as the way you construct a LocalDate matters. I guess the timezone is omitted in the ".of()" version.
The order of invoked methods seems matter.
It you invoke them by descending time-granularity (year, week of week and day of week), you get the correct result :
Note that the problem origin comes from :
that sets the week number (
1 to 53
) according to the current year.The Java
LocalDate
API cannot adapt this value if then you change the year with.withYear(year)
as the week number information is not kept in theLocalDate
instance.You can indeed see in
LocalDate
implementation thatLocalDate
instances are defined by only 3 field :year
,month
andday
.So to be precise, the important thing is that :
.withYear(year)
be invoked before