Java Data Type How to - Create TemporalAdjuster and Adjust date








Question

We would like to know how to create TemporalAdjuster and Adjust date.

Answer

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
//from   ww w  .  ja  va2  s  .  c  om
public class Main {

  public static void main(String[] args) {
    TemporalAdjuster temporalAdjuster = (Temporal t) -> t.plus(Period.ofDays(10));
    
    System.out.println(temporalAdjuster);

    TemporalAdjuster fourMinutesFromNow = temporal -> temporal.plus(4, ChronoUnit.MINUTES);

    LocalTime localTime1 = LocalTime.of(12, 0, 0);
    System.out.println(localTime1.with(temporal -> temporal.plus(4, ChronoUnit.MINUTES)));

    System.out.println(Instant.now().with(temporalAdjuster));

    LocalDate localDate1 = LocalDate.of(2013, 12, 13);
    System.out.println(localDate1.with(TemporalAdjusters.lastDayOfMonth()));

  }
}

The code above generates the following result.