Date Adjusters in Java

For scheduling applications, you often need to compute dates such as “the first Tuesday of every month.” The TemporalAdjusters class provides a number of static methods for common adjustments. You pass the result of an adjustment method to the with method. For example, the first Tuesday of a month can be computed like this:

LocalDate firstTuesday = LocalDate.of(year, month, 1).with(

TemporalAdjusters.nextOrSame(DayOfWeek.TUESDAY));

As always, the with method returns a new LocalDate object without modifying the original. The API notes at the end of this section show the available adjusters.

You can also make your own adjuster by implementing the TemporalAdjuster interface. Here is an adjuster for computing the next weekday:

TemporalAdjuster NEXT_WORKDAY = w ->

{

var result = (LocalDate) w; do

{

result = result.plusDays(1);

}

while (result.getDayOfWeek().getValue() >= 6); return result;

};

LocalDate backToWork = today.with(NEXT_WORKDAY);

Note that the parameter of the lambda expression has type Temporal, and it must be cast to LocalDate. You can avoid this cast with the ofDateAdjuster method that expects a lambda of type UnaryOperator<LocalDate>.

TemporalAdjuster NEXT_WORKDAY = TemporalAdjusters.ofDateAdjuster(w ->

{

LocalDate result = w; // No cast do

{

result = result.plusDays(1);

}

while (result.getDayOfWeek().getValue() >= 6);

return result;

});

Source: Horstmann Cay S. (2019), Core Java. Volume II – Advanced Features, Pearson; 11th edition.

Leave a Reply

Your email address will not be published. Required fields are marked *