Java Program to Display the Current Time

In the previous article, we have discussed about Java Program to Display Current Month in the (MMMM) Format

In this article we are going to see how to display the current time in Java along with suitable examples.

Java Program to Display the Current Time

Let’s see the program to understand it clearly.

Method-1: Java Program to Display the Current Time By Using Java LocalDate Class

The java.Time.LocalDate class provides inbuild “.now()” methods to format the current time in java.

Approach:

  • Create a variable of LocalTime as ‘date’.
  • Call an inbuild method of LocalTime i.e “.now()” method to get the current time and store the result in the variable “date”.
  • Print the result.

Program:

import java.time.LocalTime;
public class Main
{
    public static void main(String[] args)
    {
        // Create a variable of LocalTime as ‘date’, call an inbuild method of LocalTime “.now()” to get the current time and store the result in the variable “date”
      	LocalTime date = LocalTime.now();
        // Print the result
     	System.out.println("The current time in 24 hour format is "+ date);
    }
}
Output:

The current time in 24 hour format is 07:52:55.654615

Method-2: Java Program to Display the Current Time By Using Java Calendar Class

The java.util.Calendar class provides an inbuild method “.getInstance()” method to get the instant date-time-month from the system calendar. We can also direct get the current time in hour format using inbuild methods of calendar class i.e. calendar.get(Calendar.HOUR_OF_DAY))  represents hours in current system.

Approach:

  • Declare a variable ‘calendar’ of type Calendar and initialize it to get the system date-time using Calender.getInstance() method.
  • Print the result using inbuild methods of calendar class i.e. calendar.get(Calendar.HOUR_OF_DAY)).

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Declare a variable ‘calendar’ of type Calendar and initialize it to get the system date-time using Calendar.getInstance() method
        Calendar calendar = Calendar.getInstance();
        // Print the result using inbuild methods of calendar class
      	System.out.println("The current time in 24hour format is "+calendar.get(Calendar.HOUR_OF_DAY));
    }
}
Output:

The current time in 24hour format is 7

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output.

Related Java Programs: