Java Data Type How to - Get days, months and years between two LocalDate








Question

We would like to know how to get days, months and years between two LocalDate.

Answer

/*  w  ww.j a va 2s.  c om*/
import java.time.LocalDate;
import java.time.Period;

public class Main {
  public static void main(String[] args) {

    LocalDate firstDate = LocalDate.of(2013, 5, 17); 
    LocalDate secondDate = LocalDate.of(2015, 3, 7); 
    Period period = Period.between(firstDate, secondDate);

    System.out.println(period);
    
    int days = period.getDays(); // 18
    
    int months = period.getMonths(); // 9
    int years = period.getYears(); // 4
    boolean isNegative = period.isNegative(); // false
    
    
  }
}

The code above generates the following result.