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
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.