Java Program to display hour and minute in AM or PM


Firstly, create a Formatter and a Calendar object.

Formatter f = new Formatter();
Calendar c = Calendar.getInstance();

For AM/ PM marker, use the following conversion character −

p

Here, you can see AM/ PM marker −

f = new Formatter();
System.out.println(f.format("Hour: %tl %1$Tp", c));

The following is an example −

Example

 Live Demo

import java.util.Calendar;
import java.util.Formatter;
public class Demo {
   public static void main(String args[]) {
      Formatter f = new Formatter();
      Calendar c = Calendar.getInstance();
      System.out.println("Current date and time: "+c.getTime());
      f = new Formatter();
      System.out.println(f.format("Hour and Minute with AM/ PM: %tl:%1$tM %1$Tp", c));
      f = new Formatter();
      System.out.println(f.format("Hour: %tl %1$Tp", c));
      f = new Formatter();
      System.out.println(f.format("Minute: %1$tM", c));
   }
}

Output

Current date and time: Mon Nov 26 07:41:35 UTC 2018
Hour and Minute with AM/ PM: 7:41 AM
Hour: 7 AM
Minute: 41

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements