Oxolotl Oxolotl - 6 months ago 15
Java Question

Find last week of year with java.time

I need to find the first day of the last week of a year using Java 8 Date and Time API (java.time) and finally came to this solution:

LocalDate date = LocalDate.of(2016, 2, 17);
LocalDate lastWeekOfYear = LocalDate.of(date.getYear() + 1, 1, 7)
.with(WeekFields.ISO.weekOfYear(), 1)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).minusDays(7);


This solution finds the first week of the next year, adjusts the day of week to Monday if necessary and moves 7 days back. Is there a smarter way to achieve the same result?

Answer

As suggested, I'll answer the question myself (with a minor enhancement from the comments) as there does not seem to be a significantly simpler solution.

LocalDate date = LocalDate.of(2016, 2, 17);
LocalDate lastWeekOfYear = LocalDate.of(date.getYear() + 1, 1, 7)
    .with(WeekFields.ISO.weekOfWeekBasedYear(), 1)
    .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).minusWeeks(1);