Java 8 Display time in 12 hour AM PM format


In this Java 8 example, we will take a look at how to format and display time in 12-hour AM PM format,

package org.code2care;

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

/**
 * Display Time in Java 8 in AM PM Format
 */
public class Java8TimeAmPMFormat {

    public static void main(String[] args) {
        DateTimeFormatter dateFormat12hourAmPM;
        dateFormat12hourAmPM = DateTimeFormatter.ofPattern("hh:mm a");
        LocalTime localTime = LocalTime.now();
        System.out.println(dateFormat12hourAmPM.format(localTime));
    }
}
Output:

08:12 AM

You need to use lower case hh to display time in 0-12 hours, but if you do not use a you will not get AM/PM displayed and the time will be hard to read, hence use hh:mm a

Java 8 Display Time in AM PM using DateTimeFormatter
Java 8 Display Time in AM PM using DateTimeFormatter

Top Hashtags:

Advertisements

Advertisements




Advertisements