Display Time in 12 Hour Format With AM/PM in Java

This post shows how to display time in 12 hour format with AM/PM in Java using SimpleDateFormat and DateTimeFormatter class (Java 8 onward).

Using SimpleDateFormat

When creating a formatting pattern to display time in 12 hour format with AM/PM you need to use ‘hh’ for denoting hours and use ‘a’ for am/pm marker.

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatDate {
  public static void main(String[] args) {
    Date date = new Date();
    // Pattern 
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
    System.out.println("Time in 12 Hour format - " + sdf.format(date));
  }
}

Output

Time in 12 Hour format - 03:53:57 PM

Using DateTimeFormatter

Java 8 onward you can use new date and time API classes like LocalTime (represents time) and DateTimeFormatter for specifying pattern.

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

public class FormatDate {
  public static void main(String[] args) {
    LocalTime time = LocalTime.now();
    // Pattern 
    DateTimeFormatter pattern = DateTimeFormatter.ofPattern("hh:mm:ss a");
    System.out.println("Time in 12 Hour format - " + time.format(pattern));
  }
}

Output

Time in 12 Hour format - 03:58:07 PM

Related Posts

That’s all for the topic Display Time in 12 Hour Format With AM/PM in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.