Course contentsShow
← Java
Lesson 1883 of 2,87038. Date and Time API (java.time)Free lesson

Creating Custom TemporalAdjusters

Implementing the TemporalAdjuster functional interface to define custom date adjustment logic.

Creating Custom TemporalAdjusters

You'll learn how to implement the TemporalAdjuster functional interface to define your own date adjustment logic when the built-in adjusters don't fit your needs.

The Core Idea

While the TemporalAdjusters class provides many useful adjusters, sometimes you need business-specific date logic. Since TemporalAdjuster is a functional interface with a single method adjustInto(Temporal temporal), you can create custom adjusters using lambda expressions or method references.

Think of a TemporalAdjuster as a recipe card. The built-in adjusters are pre-printed recipes, but you can write your own recipe for any date adjustment pattern unique to your application—like "next business day" or "end of fiscal quarter."

Implementing a Custom Adjuster

The TemporalAdjuster interface requires you to implement:

Temporal adjustInto(Temporal temporal)

Here's a simple custom adjuster that moves to the next business day (skipping weekends):

TemporalAdjuster nextBusinessDay = temporal -> {
    LocalDate date = LocalDate.from(temporal);
    DayOfWeek day = date.getDayOfWeek();
    
    if (day == DayOfWeek.FRIDAY) {
        return date.plusDays(3);
    } else if (day == DayOfWeek.SATURDAY) {
        return date.plusDays(2);
    } else {
        return date.plusDays(1);
    }
};

LocalDate today = LocalDate.of(2024, 1, 5); // Friday
LocalDate next = today.with(nextBusinessDay); // Monday, Jan 8

You can also create reusable adjuster classes or static methods:

public static TemporalAdjuster addBusinessDays(int days) {
    return temporal -> {
        LocalDate date = LocalDate.from(temporal);
        int added = 0;
        while (added < days) {
            date = date.plusDays(1);
            if (date.getDayOfWeek() != DayOfWeek.SATURDAY 
                && date.getDayOfWeek() != DayOfWeek.SUNDAY) {
                added++;
            }
        }
        return date;
    };
}

Key Takeaway: Custom TemporalAdjuster implementations let you encapsulate complex date logic into reusable, chainable components using the same with() pattern as built-in adjusters.