am pm java date format

java

To format a java.time.LocalTime object as a string in the 12-hour AM/PM format, you can use the ofPattern() method of the java.time.format.DateTimeFormatter class and specify a pattern string that includes the a symbol.

Here’s an example:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        LocalTime time = LocalTime.now();
        System.out.println("Current time: " + time);

        // Format the time as a string in the 12-hour AM/PM format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm:ss a");
        String formattedTime = time.format(formatter);
        System.out.println("Formatted time: " + formattedTime);
    }
}

Here’s the output of the example code:

Current time: 10:15:30.123456789
Formatted time: 10:15:30 AM

You can customize the pattern string to include other symbols such as hh for the hour, mm for the minute, and ss for the second. The a symbol represents the AM/PM marker.

For example, the following pattern string will format the time as “10:15:30 AM EST”:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm:ss a zzzz");