Back to results for “Design Patterns in Java”
Java › Java Date & Time API (java.time)

How would you implement a custom TemporalAdjuster to calculate business-specific date logic (like 'the next business day, skipping weekends and holidays')?

Advanced

Answer

A custom TemporalAdjuster is implemented via its single functional method adjustInto(Temporal), letting you define arbitrary, business-specific date-adjustment logic (potentially incorporating an external holiday calendar lookup) that integrates seamlessly with the standard with(TemporalAdjuster) API alongside the JDK's own built-in adjusters, giving your custom business logic the same clean, declarative usage pattern as the standard library's own date calculations.
public class NextBusinessDayAdjuster implements TemporalAdjuster {
    private final Set<LocalDate> holidays;
    public NextBusinessDayAdjuster(Set<LocalDate> holidays) { this.holidays = holidays; }

    @Override
    public Temporal adjustInto(Temporal temporal) {
        LocalDate date = LocalDate.from(temporal);
        do {
            date = date.plusDays(1);
        } while (date.getDayOfWeek() == DayOfWeek.SATURDAY
              || date.getDayOfWeek() == DayOfWeek.SUNDAY
              || holidays.contains(date));
        return temporal.with(date);
    }
}

LocalDate next = today.with(new NextBusinessDayAdjuster(companyHolidays));
Real-world example A payroll processing system uses a custom NextBusinessDayAdjuster (incorporating the company's specific holiday calendar) to correctly calculate when a payment should actually be disbursed if its normally-scheduled date falls on a weekend or company holiday, integrating this business-specific rule cleanly into the same fluent date API used throughout the rest of the codebase.

Common follow-ups: How would you make this custom adjuster's holiday lookup efficient for a very large date range or high-frequency usage pattern?;What's the benefit of implementing this as a proper TemporalAdjuster versus just writing a standalone utility method with the same logic?