Monday, August 8, 2022

How to Display Time in AM-PM Format in Java

In this post we'll see how to display time in 12 hours format with AM-PM in Java.

In order to display time with AM-PM in Java, in the pattern you are creating for the format either with SimpleDateFormat (if you are not using Java 8) or with DateFormatter (if you are using Java 8) just add the pattern letter ‘a’ which denotes AM-PM of the day.

Displaying time in AM-PM format - Java SimpleDateFormat Example

If you are using the java.util.Date and SimpleDateFormat then the format you need to use to show time in AM-PM format is as following.

Date date = new Date();
// Pattern 
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a");
System.out.println("TIME - " + sdf.format(date));

Output

TIME - 13:09:55 PM

Displaying time with AM-PM format - Java DateFormatter Example

If you are using the new Date and Time API in Java 8, then you can use the DateFormatter class, pattern remains the same as used above for showing time in AM-PM format in Java.

//Getting time
LocalTime t2 = LocalTime.now();
// Pattern
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss a");
String text = t2.format(df);
System.out.println("Time - " + text);

Output

Time - 13:11:15 PM

Another example – Showing AM

LocalTime t1 = LocalTime.of(5, 30, 56);
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss a");
String text = t1.format(df);
System.out.println("Time - " + text);

Output

Time - 05:30:56 AM

That's all for this topic How to Display Time in AM-PM Format in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Format Date in Java Using SimpleDateFormat
  2. How to Convert String to Date in Java
  3. How to Convert Date And Time Between Different Time-Zones in Java
  4. How to Find Last Modified Date of a File in Java
  5. Convert int to String in Java

You may also like-

  1. Connection Pooling Using Apache DBCP in Java
  2. Producer-Consumer Java Program Using ArrayBlockingQueue
  3. Convert String to Byte Array Java Program
  4. Java Object Cloning - clone() Method
  5. Java Nested Class And Inner Class
  6. Java Reflection API Tutorial
  7. How to Resolve Local Variable Defined in an Enclosing Scope Must be Final or Effectively Final Error
  8. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example

No comments:

Post a Comment