Java Data Type How to - Add Year/Week to date/time in Java 8 with TemporalAdjuster








Question

We would like to know how to add Year/Week to date/time in Java 8 with TemporalAdjuster.

Answer

import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.WEEKS;
import static java.time.temporal.ChronoUnit.YEARS;
/*from  w  ww . j ava  2 s  . c o  m*/
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;

public class Main {
  public static void main(String[] argv) {
    LocalDate today = LocalDate.now();
    LocalDate tomorrow = today.plusDays(1);
    LocalDateTime time = LocalDateTime.now();
    LocalDateTime nextHour = time.plusHours(1);

    System.out.println("today = " + today);
    System.out.println("1) tomorrow = " + tomorrow + " \n2) tomorrow = " + today.plus(1, DAYS));
    System.out.println("local time now = " + time);
    System.out.println("1) nextHour = " + nextHour + " \n2) nextHour = " + time.plus(1, HOURS));

    LocalDate nextWeek = today.plus(1, WEEKS);
    System.out.println("Date after 1 week : " + nextWeek);

    LocalDate previousYear = today.minus(1, YEARS);
    System.out.println("Date before 1 year : " + previousYear);

    LocalDate nextYear = today.plus(1, YEARS);
    System.out.println("Date after 1 year : " + nextYear);

    LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
    System.out.println("firstDayOfMonth = " + firstDayOfMonth);
  }
}

The code above generates the following result.