Despite all the previous answers, I still had to dig around to figure out what Java8 was doing, so here is what I found the most intuitive way to do this:
LocalDate implements Temporal
with(TemporalField field, long newValue)
Returns an object of the same type as this object, with the specified modified field.
Therefore, we must tell him what part of the LocalDate date we want to change ( DAY_OF_WEEK ) and change to what value.
If in doubt, the days of the week can be counted from 0 to 6 or from 1 to 7:
System.out.printf("first day of week (0 or 1) == %d \n", ChronoField.DAY_OF_WEEK.range().getMinimum());
first day of week (0 or 1) == 1
I had to commit what my JDK provided by default - YMMV:
System.out.printf("default zone offset==[%s]\n", ZoneId.systemDefault()); System.out.printf("1st day of week==%s\n", WeekFields.of(Locale.getDefault()).getFirstDayOfWeek());
default zone offset==[Europe/London] 1st day of week==MONDAY
Therefore, if I execute some code based on these default values, like this:
LocalDate localDate = LocalDate.now(); System.out.printf("localDate == %s \n", localDate); System.out.printf("localdate first day of week == %s (%s) \n", localDate.with(ChronoField.DAY_OF_WEEK, 1), localDate.with(ChronoField.DAY_OF_WEEK, 1).getDayOfWeek());
localDate == 2017-10-24 localdate first day of week == 2017-10-23 (MONDAY)
then Java uses ChronoField.DAY_OF_WEEK which not only determines which part of the date we want to change, but also how to change it.
Therefore, if we want our code to work with what the user specifies as the first day of the week, we will create our own definition of how week-based calculations should be performed using the factory method WeekFields.of() .
Using this, we can pass our own dayOfWeek parameter to with() to calculate the date the way we want:
TemporalField myWeek = WeekFields.of(DayOfWeek.SUNDAY, 1).dayOfWeek(); System.out.printf("configured localdate first day of week == %s (%s) \n", localDate.with(myWeek, 1), localDate.with(myWeek, 1).getDayOfWeek());
configured localdate first day of week == 2017-10-22 (SUNDAY)
For a deeper understanding, take a look at the code in LocalDate.with() , it is quite interesting.