Write a Java program to get a date before and after 1 year compares to the current date


This Java program compares dates for the current year with the dates one year before and one year after. It starts by getting an instance of the Calendar class using the Calendar.getInstance() method. Then, it uses the getTime() method of the Calendar class to get the current date and assign it to the cd variable.

Next, it adds one year to the calendar instance using the Calendar.add() method and gets the resulting date with getTime(), assigning it to the ny variable. Then, it subtracts two years from the calendar instance using the Calendar.add() method and gets the resulting date with getTime(), assigning it to the py variable.

Finally, it prints out the current date, the date one year before, and the date one year after using the System.out.println() method.

Source Code

import java.util.*;
public class OneYear_Compare
{
	public static void main(String[] args)
	{
		Calendar cal = Calendar.getInstance();
		Date cd = cal.getTime(); // cd => current year		
		cal.add(Calendar.YEAR, 1); 
		Date ny = cal.getTime();	// ny => get next year		
		cal.add(Calendar.YEAR, -2); 
		Date py = cal.getTime();	//py => previous year
		System.out.println("Current Date : " + cd);
		System.out.println("Date Before One Year : " + py);
		System.out.println("Date After One Year  : " + ny);  	
	}
}

Output

Current Date : Sat Nov 05 13:41:16 IST 2022
Date Before One Year : Fri Nov 05 13:41:16 IST 2021
Date After One Year  : Sun Nov 05 13:41:16 IST 2023

Example Programs