Learn to format date and time in either 12 hours pattern. The formatted date string will have the AM-PM information as applicable to the timestamp.
1. Patterns to Display Hours
For formatting purposes, hour part of the time is represented in two ways:
- ‘hh’ – hours in 12 hour format
- ‘HH’ – hours in 24 hour format
- ‘a’ – display the AM/PM information.
Using the above information, we can create the following pattern to display time in 12-hour format including AM/PM information in formatted date string.
hh:mm:ss a
2. Demo
Java program to display the current date-time in 12-hour format. We will create examples for LocalTime
and LocalDateTime
classes.
For Date and Calendar classes, we can use SimpleDateFormat while for other classes we can use DateTimeFormatter.
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Main
{
public static void main(String[] args)
{
String pattern = "hh:mm:ss a";
//1. LocalTime
LocalTime now = LocalTime.now();
System.out.println(now.format(DateTimeFormatter.ofPattern(pattern)));
//2. LocalDateTime
LocalDateTime nowTime = LocalDateTime.now();
System.out.println(nowTime.format(DateTimeFormatter.ofPattern(pattern)));
}
}
Program output.
07:35:55 PM
07:35:55 PM
Happy Learning !!