Java 8 temporal adjusters

Java 8 gives you the ability to retrieve specific information about a date such as determining if day it is a workday or checking if a date is a company holiday with temporal queries. In addition to temporal queries, temporal adjustors were added to provide a way to manipulate a date and return the adjusted value.

In a factitious scenario, lets say we work at the Wisconsin DMV and it is required that drivers need to renew their license 90 business days after your expiration date and we need to show this date on a report. To do this we will create a custom adjuster named NinetyDayWeekendAdjuster that will implement TemporalAdjuster and override the adjustInto method. The NinetyDayWeekendAdjuster will evaluate the passed in date and return 90 days excluding weekends by creating a date 90 days in the future. By calling date.query and passing a weekend temporal query we will check if the date is either Saturday or Sunday in return adding 1 day.

public class NinetyDayWeekendAdjuster implements TemporalAdjuster {

    @Override
    public Temporal adjustInto(Temporal temporal) {

        LocalDateTime currentDateTime = LocalDateTime.from(temporal);

        // 90 days into the future
        LocalDateTime futureDate = LocalDateTime.from(temporal).plus(90,
                ChronoUnit.DAYS);

        // loop through date range checking if the date 
        // is Saturday or Sunday by using the WeekendQuery
        // if it is, add one day to account for the business day
        for (LocalDateTime startDate = currentDateTime; startDate
                .isBefore(futureDate); startDate = startDate.plusDays(1)) {

            if (startDate.query(new WeekendQuery())) {
                futureDate = futureDate.plusDays(1);
            }
        }
        return futureDate;
    }
}

We then can invoke the adjuster by calling the with method defined in the temporal-based classes.

@Test
public void test() {

    LocalDateTime currentDateTime = LocalDateTime.of(2014, Month.APRIL, 30,
            0, 0);

    LocalDateTime adjustedDate = currentDateTime
            .with(new NinetyDayWeekendAdjuster());

    assertEquals(LocalDateTime.of(2014, Month.SEPTEMBER, 3, 0, 0),
            adjustedDate);

}

The java 8 date TemporalAdjuster interface allows a clean way to apply logic or ask questions about an existing date.