Write a Java program to compute the difference between two dates


This program calculates the difference between two LocalDate instances, specifically the difference in years, months, and days. The program starts by importing the java.time package, which contains the LocalDate and Period classes used in the program.

In the main method, two LocalDate instances are created using the of method of the LocalDate class. The first instance is created with the date June 8, 2014, and the second instance is created using the now method of the LocalDate class, which sets the date to the current system date.

Next, a Period instance is created using the between method of the Period class, which takes two LocalDate instances as arguments and calculates the difference between them in years, months, and days.

Finally, the program prints the difference in years, months, and days using the getYears(),getMonths(), and getDays() methods of the Period class, respectively.

Source Code

import java.time.*;
class Difference_YearMonthDay
{  
	public static void main(String[] args)
	{
		LocalDate pdt = LocalDate.of(2014, 06, 8);
		LocalDate cdt = LocalDate.now(); 
		Period dif = Period.between(pdt, cdt);
		System.out.println("Years :"+dif.getYears());
		System.out.println("Months :"+dif.getMonths());
		System.out.println("Days :"+dif.getDays());
	}
}

Output

Years :8
Months :4
Days :28

Example Programs