Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 896

How to Format Time in AM-PM Format - Java Program

$
0
0

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

  1. How to 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. Converting int to string - Java Program

You may also like -

>>>Go to Java Programs page


Viewing all articles
Browse latest Browse all 896

Trending Articles