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
You may also like-
No comments:
Post a Comment