Java Get AM/PM information from LocalDateTime instance


In Java 8, you can get the AM/PM information from a LocalDateTime instance by formatting it with a DateTimeFormatter object that includes the a pattern symbol. The a pattern symbol represents the AM/PM marker.

Here’s an example:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeAMPMExample {
    public static void main(String[] args) {
        // create a LocalDateTime object
        LocalDateTime localDateTime = LocalDateTime.now();

        // create a DateTimeFormatter object with the desired format including the AM/PM marker
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a");

        // format the LocalDateTime object with the formatter to get the AM/PM information
        String amPm = localDateTime.format(formatter);

        // print the AM/PM information
        System.out.println(amPm.substring(amPm.length() - 2));
    }
}

In this example, we’re creating a DateTimeFormatter object with the pattern "yyyy-MM-dd hh:mm:ss a", which includes the AM/PM marker. Then we’re using the format() method to format the LocalDateTime object with the formatter to get the AM/PM information. Finally, we’re using the substring() method to get the last 2 characters of the formatted datetime string, which represent the AM/PM marker.

Note that the hh pattern symbol is used instead of HH because we want the hour to be displayed in 12-hour format instead of 24-hour format.