Write a Java program to create a Date object using the Calendar class


This Java program creates a new Calendar instance, sets its date to January 18th, 2022, and then prints out the resulting Date object using the getTime() method.

The program uses the following steps to set the date of the Calendar instance:

  • Call Calendar.clear() to clear any existing date and time values in the Calendar instance.
  • Call Calendar.set(Calendar.YEAR, year) to set the year value to 2022.
  • Call Calendar.set(Calendar.MONTH, month) to set the month value to 0, which represents January.
  • Call Calendar.set(Calendar.DATE, date) to set the day of the month to 18.

Finally, the program prints out the resulting Date object using the getTime() method, which returns a Date object that represents the same point in time as the Calendar instance.

Note that the program does not prompt the user for input or perform any other meaningful computation beyond setting and printing out a specific date. Also, the program uses the default time zone and locale settings of the Calendar instance, which may not be appropriate in all contexts.

Source Code

import java.util.*;
public class DataObj_UseCal
{
	public static void main(String[] args)
	{
		int year = 2022;
		int month = 0; //0-Jan to 11-Dec
		int date = 18;
		Calendar cal = Calendar.getInstance();
		cal.clear();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month);
		cal.set(Calendar.DATE, date);
		System.out.println(cal.getTime());
	}
}

Output

Tue Jan 18 00:00:00 IST 2022

Example Programs