Java Data Type How to - Add duration to date and check exception








Question

We would like to know how to add duration to date and check exception.

Answer

import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
// w  w w  .j  a  v  a2  s  .c  o m
public class Main {

  public static void main(String[] args) {
    LocalDate localDate = LocalDate.of(2012, 11, 23);
    System.out.println(localDate.plus(3, ChronoUnit.DAYS)); //2012-11-26

    System.out.println(localDate.plus(Period.ofDays(3)));  //2012-11-26
    try {
        System.out.println(localDate.plus(Duration.ofDays(3)));

        System.out.println(localDate.plus(4, ChronoUnit.FOREVER));
    } catch (UnsupportedTemporalTypeException e) {
        e.printStackTrace();
    }
  }
}

The code above generates the following result.