Skip to main content

Display Time in 24 Hour Format in Java

This post shows how to display time in 24 hour format in Java using SimpleDateFormat and DateTimeFormatter class (Java 8 onward).

Pattern for time in 24 hour format

In Java pattern for 24 hours are as follows-

  • H- Hour in day (0-23), will return 0-23 for hours.
  • k- Hour in day (1-24), will return 1-24 for hours.

As per your requirement for displaying time use the appropriate hour pattern.

Using SimpleDateFormat

Date date = new Date();
// Pattern 
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println("Time in 24 Hour format - " + sdf.format(date));
Output
Time in 24 Hour format – 16:13:58

Here is another program which shows the difference between using ‘HH’ and ‘kk’ as an hour format.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class FormatDate {
  public static void main(String[] args) {
    Date date = new GregorianCalendar(2019, Calendar.SEPTEMBER, 15, 24, 20, 15).getTime();
    System.out.println("DateTime is- " + date);
    // Pattern 
    SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MMM-yyyy kk:mm:ss");
    SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
    System.out.println("Time in 24 Hour format - " + sdf1.format(date));
    System.out.println("Time in 24 Hour format - " + sdf2.format(date));
  }
}
Output
DateTime is- Mon Sep 16 00:20:15 IST 2019
Time in 24 Hour format - 16-Sep-2019 24:20:15
Time in 24 Hour format - 16-Sep-2019 00:20:15

Using DateTimeFormatter

Java 8 onward you can use new date and time API classes like LocalTime for representing time and DateTimeFormatter for specifying pattern.

LocalTime time = LocalTime.now();
// Pattern 
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println("Time in 24 Hour format - " + time.format(pattern));
Output
Time in 24 Hour format - 16:28:08

That's all for the topic Display Time in 24 Hour Format in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like