Java Date Time Adjuster








We may want to adjust a date and time to the first Monday of the month, or the next Tuesday.

We can adjust date and time using TemporalAdjuster interface. The interface has one method, adjustInto(), which takes a Temporal and returns a Temporal.

TemporalAdjusters class contains static methods that return different types of predefined date adjusters.

The following code shows how to compute the first Monday after January 1, 2014:

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;
//from   w  ww . j a v  a  2 s. com
public class Main {

  public static void main(String[] args) {
    LocalDate ld1  = LocalDate.of(2014, Month.JANUARY,  1);
    LocalDate ld2  = ld1.with(TemporalAdjusters.next(DayOfWeek.MONDAY)); 
    System.out.println(ld1);
    System.out.println(ld2);

  }
}

The code above generates the following result.





TemporalAdjusters

TemporalAdjusters defines some useful methods we can use to adjust date.

  • next(DayOfWeek dayOfWeek)
  • nextOrSame(DayOfWeek dayOfWeek)
  • previous(DayOfWeek dayOfWeek)
  • previousOrSame(DayOfWeek dayOfWeek)
  • firstInMonth(DayOfWeek dayOfWeek)
  • lastInMonth(DayOfWeek dayOfWeek)
  • dayOfWeekInMonth(int ordinal, DayOfWeek dayOfWeek)
  • firstDayOfMonth()
  • lastDayOfMonth()
  • firstDayOfYear()
  • lastDayOfYear()
  • firstDayOfNextMonth()
  • firstDayOfNextYear()
  • ofDateAdjuster(UnaryOperator<LocalDate> dateBasedAdjuster)

The following code shows how to use dayOfWeekInMonth.

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;
// w  w  w  .  j av  a 2  s .c  o  m
public class Main {

  public static void main(String[] args) {
    LocalDate ld1  = LocalDate.of(2014, Month.MAY,  21);
    System.out.println(ld1);
    LocalDate ld2  = ld1.with(TemporalAdjusters.dayOfWeekInMonth(5, DayOfWeek.SUNDAY));
    System.out.println(ld2);
  }
}

The code above generates the following result.





Custom Adjusters

You can use the ofDateAdjuster() method to create your own date adjuster for a LocalDate.

The following code creates a date adjuster.

import java.time.LocalDate;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
/*from  ww  w. j a va 2s  .  c o m*/
public class Main {

  public static void main(String[] args) {
    // Create an adjuster that retruns a date after 3 months and 2 days
    TemporalAdjuster adjuster = TemporalAdjusters
        .ofDateAdjuster((LocalDate date) -> date.plusMonths(3).plusDays(2));

    LocalDate today = LocalDate.now();
    LocalDate dayAfter3Mon2Day = today.with(adjuster);
    System.out.println("Today: " + today);
    System.out.println("After 3  months  and  2  days: " + dayAfter3Mon2Day);

  }
}

The code above generates the following result.