Format date/timestamp in 12 hours pattern

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. Available patterns for hour part of time

For formatting purpose, hour part of the time is represented in two ways:

  • ‘hh’ – hours in 12 hour format
  • ‘HH’ – hours in 24 hour format

Additionally, we can use ‘a’ to display the AM/PM information.

Using above information, we can create following pattern to display time in 12 hour format including AM/PM information in formatted date string.

hh:mm:ss a

2. Java example to format date in 12 hours pattern

Java program to display the current date time in 12 hour format. We will create the examples for LocalTime, LocalDateTime, ZonedDateTime, Date and Calendar classes.

For Date and Calendar classes, we will use SimpleDateFormat while for other classes we will use DateTimeFormatter.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

public class Main 
{
    public static void main(String[] args) 
    {
        String pattern = "hh:mm:ss a";
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        
        //1. LocalDate
        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)));
        
        //3. ZonedDateTime
        ZonedDateTime zonedTime = ZonedDateTime.now();
        System.out.println(zonedTime.format(DateTimeFormatter.ofPattern(pattern)));
        
        //4. Date
        Date today = new Date();
        System.out.println(dateFormat.format(today));
        
        //4. Calendar
        Calendar calToday = Calendar.getInstance();
        System.out.println(dateFormat.format(calToday.getTime()));
    }
}

Program output.

07:35:55 PM
07:35:55 PM
07:35:55 PM
07:35:55 PM
07:35:55 PM

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.