0

I want to get the day on which the first Monday of a specific ISO year will be.

I have an int variable representing the year, and I want to compute a LocalDate representing the first Monday in that ISO year (following ISO 8601). I'm referring to the following concept: First week (ISO week date). So the Monday of the first ISO week can be in December.

Is there an elegant way to do this, similar to the answer of the following question? Get the first Monday of a month

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Hermann.Gruber
  • 1,257
  • 1
  • 12
  • 37

1 Answers1

4

You can do this with the temporal fields defined in WeekFields.ISO.

First create a LocalDate in the desired year, then adjust it to the first week, then adjust it to the first day of the week:

LocalDate localDate = LocalDate.ofYearDay(2020, 1);
System.out.println(
    localDate
        .with(WeekFields.ISO.weekOfWeekBasedYear(), 1)
        .with(WeekFields.ISO.dayOfWeek(), 1)
);

Result:

2019-12-30
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • I find it funny and a bit surprising that this works. The first day of 2020 is in week 53 of week-based year 2009, so I would have expected `.with(WeekFields.ISO.weekOfWeekBasedYear(), 1)` to give us week 1 of 2009, but it does give us week 1 of 2010. To avoid the reader wondering and being uncertain about what happens I always start out from a later day in the year (say, day 10 of the year) and adjust the day-of-week first (which is then guaranteed to keep us inside the same year and the same week-based year) and then the week number afterwards. – Ole V.V. Mar 14 '23 at 10:17
  • The use of `WeekFields.ISO` is very good. Being explicit about the definition of weeks that the code uses gives good clarity and should leave no one in doubt. – Ole V.V. Mar 14 '23 at 10:20
  • 1
    @OleV.V. Now that you pointed it out, this is indeed kind of weird! I didn't even notice that while posting this! Perhaps adding a `.with(WeekFields.ISO.weekBasedYear(), desiredYear)` at the start could also help clarify things. – Sweeper Mar 14 '23 at 10:27
  • thanks, this is exactly the kind of code I was looking for! – Hermann.Gruber Mar 14 '23 at 10:32