1

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.

User1254
  • 85
  • 5
  • 1
    *-Duser.region=UK* should be `-Duser.country=GB` I think. I get the expected outputs, run for Locales it_IT and en_GB – g00se Aug 31 '21 at 10:29
  • You're right. Just tested and works. Such a bad mistake, thank you for helping. If you want you can answer so I can mark as resolved. – User1254 Aug 31 '21 at 10:33
  • Can't unfortunately. It's been closed – g00se Aug 31 '21 at 10:46
  • The links provided by the the private feedback didn't help as much as your comment. That's unfortunate.. – User1254 Aug 31 '21 at 10:55
  • 1
    Yes, there's a lot of early question-closing here, but I understand that erring on the side of caution is better than having gazillions of questions that are essentially duplicates – g00se Aug 31 '21 at 10:57

0 Answers0