Get current time information in Java

Java 8Object Oriented ProgrammingProgramming

Import the following package for to work with Calendar class in Java,

import java.util.Calendar;

Create a calendar class now.

Calendar cal = Calendar.getInstance();

To display entire time information, use the following fields.

cal.get(Calendar.HOUR_OF_DAY)
cal.get(Calendar.HOUR)
cal.get(Calendar.MINUTE)
cal.get(Calendar.SECOND)
cal.get(Calendar.MILLISECOND)

The following is the final example.

Example

 Live Demo

import java.util.Calendar;
public class Demo {
   public static void main(String[] args) {
      Calendar cal = Calendar.getInstance();
      // current date and time
      System.out.println(cal.getTime().toString());
      // time information
      System.out.println("Hour (24 hour format) : " + cal.get(Calendar.HOUR_OF_DAY));
      System.out.println("Hour (12 hour format) : " + cal.get(Calendar.HOUR));
      System.out.println("Minute : " + cal.get(Calendar.MINUTE));
      System.out.println("Second : " + cal.get(Calendar.SECOND));
      System.out.println("Millisecond : " + cal.get(Calendar.MILLISECOND));
   }
}

Output

Mon Nov 19 13:42:44 UTC 2018
Hour (24 hour format) : 13
Hour (12 hour format) : 1
Minute : 42
Second : 44
Millisecond : 621
raja
Published on 17-Dec-2018 14:46:46
Advertisements