Write a Java program to get year and months between two dates


This program calculates the difference between two dates in terms of years and months using the Period class in the java.time package.

The program first gets the current date using LocalDate.now() and stores it in a variable called today. It then creates another LocalDate object called userday representing a specific date, in this case November 29, 2020.

To calculate the difference between the two dates, it uses the Period.between() method and passes in the two LocalDate objects as arguments. The method returns a Period object that represents the difference between the two dates in terms of years, months, and days.

The program then retrieves the number of years and months from the Period object using the getYears() and getMonths() methods, respectively, and prints the result to the console using System.out.println(). The output will display the difference between the two dates in terms of years and months.

Source Code

import java.time.*;
public class YearMonth_TwoDates
{
	public static void main(String[] args)
	{
		LocalDate today = LocalDate.now();    
		LocalDate userday = LocalDate.of(2020, Month.NOVEMBER, 29); 
		Period diff = Period.between(userday, today); 
		System.out.println("\nDifference between "+ userday +" and "+ today +": " 
		+ diff.getYears() +" Years and "+ diff.getMonths() +" Months");
	}
}

Output

Difference between 2020-11-29 and 2022-11-05: 1 Years and 11 Months

Example Programs