Google News
logo
Java Program to Format Time in AM-PM format
In the following example of Java program to format time in AM/PM format using the java.time package :
Program :
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class FormatTime {
    public static void main(String[] args) {
        // Get the current time
        LocalTime now = LocalTime.now();
        
        // Format the time in AM/PM format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a");
        String formattedTime = now.format(formatter);
        
        // Print the formatted time
        System.out.println("Current time in AM/PM format: " + formattedTime);
    }
}
Output :
Current time in AM/PM format: 12:10:53 PM
This program creates a LocalTime object representing the current time using the now() method of the LocalTime class. It then uses the ofPattern() method of the DateTimeFormatter class to create a formatter object with the desired time pattern, including the a pattern symbol to specify the AM/PM marker.

Finally, it formats the time using the formatter object and prints it to the console.