Write a Java Program to Increment a Month using the Calendar Class


This Java program demonstrates how to increment a date by a specified number of months using the Calendar class. The program first creates a new instance of Calendar using the getInstance() method, which returns a calendar object set to the current date and time. The program then prints the current date and time using the getTime() method of the Calendar class.

To increment the date by five months, the program calls the add() method of the Calendar class, passing in the Calendar.MONTH field and a value of five. This adds five months to the current date and time stored in the Calendar object. Finally, the program prints the updated date and time using the getTime() method of the Calendar class.

Overall, this program provides a simple example of how to increment a date by a specified number of months using the Calendar class in Java. However, it is worth noting that the Calendar class has been replaced by the newer java.time API in Java 8 and later versions, which provides more flexible and robust date and time handling capabilities.

Source Code

import java.util.Calendar;
class Increment_Month
{
	public static void main(String[] args)
	{
		Calendar cal = Calendar.getInstance();
		System.out.println("Current Date : " + cal.getTime());
		cal.add(Calendar.MONTH, 5);
		System.out.println("Updated Date (5 Months) : " + cal.getTime());
	}
}

Output

Current Date : Sat Nov 05 14:37:28 IST 2022
Updated Date (5 Months) : Wed Apr 05 14:37:28 IST 2023

Example Programs