Display entire date time with milliseconds in Java

Java 8Object Oriented ProgrammingProgramming

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

import java.util.Calendar;

To display the entire day time, firstly create a Calendar object.

Calendar cal = Calendar.getInstance();

Display the entire date time using the fields shown below −

// DATE
Calendar.YEAR
Calendar.MONTH
Calendar.DATE
// TIME
Calendar.HOUR_OF_DAY
Calendar.HOUR
Calendar.MINUTE
Calendar.SECOND
Calendar.MILLISECOND

The following is the complete 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());
      // date information
      System.out.println("\nDate Information..........");
      System.out.println("Year = " + cal.get(Calendar.YEAR));
      System.out.println("Month = " + (cal.get(Calendar.MONTH) + 1));
      System.out.println("Date = " + cal.get(Calendar.DATE));;
      // time information
      System.out.println("\nTime 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 14:03:34 UTC 2018

Date Information..........
Year = 2018
Month = 11
Date = 19

Time Information..........
Hour (24 hour format) : 14
Hour (12 hour format) : 2
Minute : 3
Second : 34
Millisecond : 959
raja
Published on 17-Dec-2018 14:51:23
Advertisements