Display Hour and Minute in AM or PM in Java



In this article, we will learn how to format date and time in Java using the Formatter and Calendar classes. The Formatter class allows for flexible string formatting, and the Calendar class is useful for retrieving and manipulating date and time values. We will use these classes to display the current hour, minute, and AM/PM marker.

Problem Statement

Given a Calendar instance, write a Java program to display the current hour, minute, and AM/PM marker using the Formatter class.
Input
The program fetches the current date and time using the Calendar class.
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

Steps to format the current time with AM/PM

The following are the steps to format the current time with AM/PM

  • Import the necessary classes: Formatter and Calendar from java.util package.
  • Create an instance of Formatter to format the output.
  • Fetch the current date and time using Calendar.getInstance().
  • Use format specifiers in the Formatter class to print the hour, minute, and AM/PM marker.
  • Display the formatted output.

Java Program to format date and time using Formatter

The following is an example of formatting date and time using Formatter

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

Code Explanation

In the program, a Calendar object is used to get the current date and time. The Formatter class formats the output using specifiers like %tl for 12-hour format, %tM for minutes, and %Tp for the AM/PM marker. The formatted output displays the current hour, minute, and AM/PM marker.

Updated on: 2024-11-07T01:06:05+05:30

432 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements