All 15 Java Date & Time API (java.time) questions
More in Java Date & Time API (java.time)
Advertisement
Java › Java Date & Time API (java.time)

How would you use TemporalAdjusters to compute dates like 'the next Monday' or 'the last day of the month' relative to a given LocalDate?

Intermediate

Answer

TemporalAdjusters provides a collection of pre-built, common date-adjustment strategies (nextOrSame(DayOfWeek), lastDayOfMonth(), firstDayOfNextMonth(), and several others) usable via LocalDate's with(TemporalAdjuster) method, expressing common calendrical calculations declaratively and readably rather than hand-writing the underlying day-counting/comparison logic yourself, which is both more concise and considerably less error-prone (avoiding subtle off-by-one or month-boundary bugs that manual date arithmetic is notoriously prone to).
LocalDate today = LocalDate.of(2024, 6, 15);  // a Saturday

LocalDate nextMonday = today.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
LocalDate firstDayOfNextMonth = today.with(TemporalAdjusters.firstDayOfNextMonth());

System.out.println(nextMonday);        // 2024-06-17
System.out.println(lastDayOfMonth);    // 2024-06-30
Real-world example A billing system calculating each customer's next invoice date (always the last day of the current month) uses TemporalAdjusters.lastDayOfMonth() rather than hand-writing month-length-aware logic (which would need to separately account for February, leap years, and months with 30 versus 31 days), eliminating an entire category of manual calendar-arithmetic bugs.

Common follow-ups: How would you write a completely custom TemporalAdjuster for a business-specific date rule not covered by the built-in ones (like 'next business day, skipping weekends')?;What's the difference between TemporalAdjusters.next() and nextOrSame() for a date that already falls on the target day of week?