Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Tuesday, December 1, 2020

Java Program To Display Time In 24-hour Format

1. Overview

In this tutorial, we'll learn how to display the current time in 24 hours format.

Java Program To Display Time In 24-hour Format


2. Java Program To Display Time In 24-hour Format


Follow the below steps to format the new Date() into 24 hours format.

Steps:

Step 1: Create the current date and time using new Date().
Step 2: Create date formatter using SimpleDateFormat with "kk:mm:ss"
Step 3: Next, call formatter.format() method to get the date in the 24 hours string format.
package com.javaprogramto.java8.dates.format;

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

public class FormatTIme24HoursExample {

	public static void main(String[] args) {

		// Getting the current date and time
		Date currentDate = new Date();
		
		// Creating simple date formatter to 24 hours
		SimpleDateFormat formatter = new SimpleDateFormat("kk:mm:ss");
		
		// getting the time in 24 hours format
		String timeIn24Hours = formatter.format(currentDate);
		
		// printing the time
		System.out.println("Current time in 24 hours format : "+timeIn24Hours);
	}
}
 
Output:
Current time in 24 hours format : 21:19:26
 
In the above program, we can use the "HH:mm:ss" instead of "kk:mm:ss". But the main difference between kk and HH is k indicates hours from 1 to 24 where as H indicates hours in rage 0-23. Midnight indicates by k as 24 and H as 0.

3. Conclusion


In this quick article, we've seen how to display the time in 24 hours format.

No comments:

Post a Comment

Please do not add any spam links in the comments section.