I need to get the first and the last day of a date composed by a year and a week. I tried this code:
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class MyClass {
public static void main(String args[]) {
WeekFields weekFields = WeekFields.of(Locale.getDefault());
int year = 2021;
int week = 29;
// first day of the week
System.out.println(LocalDate.now()
.withYear(year)
.with(weekFields.weekOfYear(), week)
.with(weekFields.dayOfWeek(), 1));
// last day of the week
System.out.println(LocalDate.now()
.withYear(year)
.with(weekFields.weekOfYear(), week)
.with(weekFields.dayOfWeek(), 7));
}
}
My default Locale is it_IT and the output was correct, first day was 19/07/2021 and last day was 25/07/2021 (year week IT, format is dd/mm/yyyy).
I stopped the application and before running it I set the VM arguments -Duser.language=en -Duser.region=UK to test a different Locale but once run again the output was completely wrong.
For the week 29 of the year 2021 I expected the first day of the week to be 2021-07-19 and the last day 2021-07-25 (year week UK) but I instead got 2021-07-11 as the first day of the week and 2021-07-17 as the last day of the week.
What am I missing? Thank you.