Java Program to display Time in 12-hour format

Java 8Object Oriented ProgrammingProgramming

Use the SimpleDateFormat class to display time in 12-hour format.

Set the format

Date dt = new Date();
SimpleDateFormat dateFormat;
dateFormat = new SimpleDateFormat("hh:mm:ss a");

Now, the following will display time in 12-hour format

dateFormat.format(dt)

The following is an example

Example

 Live Demo

import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
   public static void main(String[] argv) throws Exception {
      Date dt = new Date();
      SimpleDateFormat dateFormat;
      dateFormat = new SimpleDateFormat("hh:mm:ss a");
      System.out.println("Time in 12 hr format = "+dateFormat.format(dt));
   }
}

Output

Time in 12 hr format = 11:33:53 AM
raja
Published on 19-Dec-2018 14:37:32
Advertisements