Java 8 – Difference between two LocalDate


In Java 8, we can use Period.between(startDate, endDate) method to find out the difference between two LocalDate instances. Period is a final class introduced in JDK 1.8 and its static method between(startDate, endDate) return the period between the start date and end date.

Note:

  • The result of this method can be a negative period if the end is before the start.
  • The negative sign will be the same in each year, month and day.
LocalDateDiff.java
package org.websparrow.java8;

import java.time.LocalDate;
import java.time.Month;
import java.time.Period;

public class LocalDateDiff {

	public static void main(String[] args) {

		LocalDate startDate = LocalDate.of(1947, Month.AUGUST, 15);

		LocalDate endDate = LocalDate.of(1950, Month.JANUARY, 26);

		Period period = Period.between(startDate, endDate);

		System.out.println("years:" + period.getYears());
		System.out.println("months:" + period.getMonths());
		System.out.println("days:" + period.getDays());
	}
}
Console
years:2
months:5
days:11

References

  1. Java 8 – Calculate difference between two LocalDateTime
  2. Java 8– Calculate date & time difference between two Zone
  3. Display all ZoneId in Java 8
  4. Class LocalDate
  5. Class Period

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.