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

Chaining Adjusters with with()

Combining multiple temporal adjusters using the with() method to perform complex date calculations.

Chaining Adjusters with with()

You'll learn how to combine multiple temporal adjusters in sequence to perform complex date calculations with readable, fluent code.

The Core Idea

The with() method on temporal objects returns a new instance, which means you can chain multiple with() calls together. Each adjustment builds on the previous result, allowing you to compose complex date logic from simple, reusable adjusters.

Think of it like giving GPS directions: "Start here, then go to the nearest coffee shop, then find the next Monday, then move to the first day of that month." Each step transforms your location based on the previous one.

How Chaining Works

Since temporal objects are immutable, each with() call returns a new object. This makes chaining natural and safe:

LocalDate today = LocalDate.of(2024, 3, 15);  // Friday, March 15

// Chain multiple adjustments
LocalDate result = today
    .with(TemporalAdjusters.next(DayOfWeek.MONDAY))      // Next Monday (March 18)
    .with(TemporalAdjusters.lastDayOfMonth())             // Last day of March (March 31)
    .with(TemporalAdjusters.firstDayOfNextMonth());       // First day of April (April 1)

System.out.println(result);  // 2024-04-01

Each adjustment operates on the result of the previous one. You're not modifying the original date; you're creating a pipeline of transformations.

Practical Example: Business Logic

LocalDate paymentDate = LocalDate.now()
    .with(TemporalAdjusters.lastDayOfMonth())             // End of this month
    .with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));  // Previous Friday

// Find second Tuesday of next month
LocalDate meetingDate = LocalDate.now()
    .with(TemporalAdjusters.firstDayOfNextMonth())
    .with(TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.TUESDAY));

Key Takeaway: Chaining with() calls lets you build complex date calculations from simple, reusable adjusters, creating readable code that applies transformations step-by-step to immutable temporal objects.