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
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
- Display Time in 24 Hour Format in Java
- LocalDateTime in Java With Examples
- Merge Sort Java Program
- Java Program to Display Armstrong Numbers
- Java throws Clause With Examples
- Java Stream Collectors.partitioningBy() Examples
- Predefined Mapper and Reducer Classes in Hadoop
- Installing Node.js and NPM on Windows
No comments:
Post a Comment