Write a Java program to get todays date at midnight time


This Java program demonstrates how to get the midnight time of the current day using the Calendar class.

  • The program starts by creating a new instance of GregorianCalendar, which is a subclass of Calendar that follows the standard calendar system.
  • Next, the program sets the HOUR_OF_DAY, MINUTE, and SECOND fields of the Calendar object to zero, representing the start of the day.
  • Finally, the program prints the midnight time by calling the getTime() method of the Calendar object, which returns a Date object representing the specified time.

Overall, the program retrieves the current date and time and sets the time to midnight, effectively extracting the midnight time of the current day.

Source Code

import java.util.*;
class Midnight_Time
{
	public static void main(String[] args)
    {
      Calendar cal = new GregorianCalendar();
      cal.set(Calendar.HOUR_OF_DAY, 0);
      cal.set(Calendar.MINUTE, 0);
      cal.set(Calendar.SECOND, 0);
      System.out.println(cal.getTime());
 
    }
}

Output

Sat Nov 05 00:00:00 IST 2022

Example Programs