In this post I’ll show how you can format time in AM-PM format.
In order to get time in AM-PM format, in the format you are creating using SimpleDateFormat (if you are not using Java 8) or DateFormatter (if you are using Java 8) just add the pattern letter ‘a’ which denotes AM-PM of the day.
Example Code using SimpleDateFormat
If you are using the java.util.Date and SimpleDateFormat
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
Example code using DateFormatter
If you are using the new Date and Time API in Java 8, then you can use the DateFormatter class, pattern remains the same.
//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 format time in AM-PM format. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -