How do I create a custom TemporalAdjuster?

In this example we are going to learn how to implement a custom TemporalAdjuster. We are going to create TemporalAdjuster to find the next working day from a specified date. We will use 5 working days, from Monday to Friday.

The custom temporal adjuster class should implement the TemporalAdjuster interface, which define a single method that we must implement, the adjustInto(Temporal) method.

package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;

public class NextWorkingDayAdjuster implements TemporalAdjuster {
    @Override
    public Temporal adjustInto(Temporal temporal) {
        int field = temporal.get(ChronoField.DAY_OF_WEEK);
        DayOfWeek dayOfWeek = DayOfWeek.of(field);

        int daysToAdd = 1;
        if (DayOfWeek.FRIDAY.equals(dayOfWeek)) {
            daysToAdd = 3;
        } else if (DayOfWeek.SATURDAY.equals(dayOfWeek)) {
            daysToAdd = 2;
        }
        return temporal.plus(daysToAdd, ChronoUnit.DAYS);
    }
}

The NextWorkingDayAdjuster move the temporal object a day forward. Except if it is on Friday or Saturday, which will move the temporal object three days or two days forward respectively. This will make it return Monday as the next working day.

After creating the custom adjuster, now let’s create an example that use the NextWorkingDayAdjuster class.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjuster;

public class NextWorkingDayAdjusterDemo {
    public static void main(String[] args) {
        TemporalAdjuster nextWorkingDay = new NextWorkingDayAdjuster();

        LocalDate now = LocalDate.now();
        LocalDate nextDay = now.with(nextWorkingDay);
        System.out.println("now            = " + now);
        System.out.println("nextWorkingDay = " + nextDay);

        LocalDate friday = LocalDate.of(2021, Month.MARCH, 11);
        nextDay = friday.with(nextWorkingDay);
        System.out.println("friday         = " + friday);
        System.out.println("nextWorkingDay = " + nextDay);

        LocalDate saturday = LocalDate.of(2021, Month.MARCH, 12);
        nextDay = saturday.with(nextWorkingDay);
        System.out.println("saturday       = " + saturday);
        System.out.println("nextWorkingDay = " + nextDay);
    }
}

And here are the results of our code:

now            = 2021-11-18
nextWorkingDay = 2021-11-19
friday         = 2021-03-11
nextWorkingDay = 2021-03-12
saturday       = 2021-03-12
nextWorkingDay = 2021-03-15
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.