How to get days, months and years between two Java LocalDate?


Set the two Java dates:

LocalDate date1 = LocalDate.of(2019, 3, 25);
LocalDate date2 = LocalDate.of(2019, 4, 29);

Now, get the difference between two dates with Period class between() method:

Period p = Period.between(date1, date2);

Now, get the years, month and days:

p.getYears()
p.getMonths()
p.getDays()

Example

import java.time.LocalDate;
import java.time.Period;
public class Demo {
   public static void main(String[] args) {
      LocalDate date1 = LocalDate.of(2019, 3, 25);
      LocalDate date2 = LocalDate.of(2019, 4, 29);
      System.out.println("Date 1 = "+date1);
      System.out.println("Date 2 = "+date2);
      Period p = Period.between(date1, date2);
      System.out.println("Period = "+p);
      System.out.println("Years (Difference) = "+p.getYears());
      System.out.println("Month (Difference) = "+p.getMonths());
      System.out.println("Days (Difference) = "+p.getDays());
   }
}

Output

Date 1 = 2019-03-25
Date 2 = 2019-04-29
Period = P1M4D
Years (Difference) = 0
Month (Difference) = 1
Days (Difference) = 4

Updated on: 30-Jul-2019

790 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements