Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Tuesday, December 1, 2020

SimpleDateFormat - kk VS HH VS hh in Date Formatting Java

1. Overview

In this tutorial, We'll learn understand the main difference between the kk, HH and hh in date formatting in java.

You might have used these in the date formatting in java working with SimpleDateFormat.

First, understand the diff kk VS HH VS hh in java. Next, we'll look into the example programs.

SimpleDateFormat -  kk VS HH VS hh in Date Formatting Java


2. Understand kk VS HH vs hh in SimpleDateFormat

All of these 3 indicates the hours in date but there a little importance to know about each.

If you know the meaning of each one and what is range of values are considered then you are good with these formatters.

kk - hours - range (1 to 24) - hours in 24 hours format

HH - hours - range (0 to 23) - hours in 24 hours format

hh - hours - range (1 to 12) - hours in 12 hours format with AM/PM


3.  Example on kk VS HH VS hh 

let us write a simple program to understand each one and how it produces the date format.


package com.javaprogramto.java8.dates.format;

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

public class FormatDiffkkVShhVsHH {

	public static void main(String[] args) {

		// Creating the Date object
		Date date = new Date(2020, 12, 1, 00, 30, 30);
		System.out.println("Example date 1 : " + date);

		// Example with kk
		SimpleDateFormat formatkk = new SimpleDateFormat("kk:mm:ss");
		String kkValue = formatkk.format(date);
		System.out.println("Date Time format with kk : " + kkValue);

		// Example with HH
		SimpleDateFormat formatHH = new SimpleDateFormat("HH:mm:ss");
		String HHValue = formatHH.format(date);
		System.out.println("Date Time format with HH : " + HHValue);

		// Example with hh
		SimpleDateFormat formathh = new SimpleDateFormat("hh:mm:ss a");
		String hhValue = formathh.format(date);
		System.out.println("Date Time format with hh : " + hhValue);
	}
}
 

Output:

Example date 1 : Sat Jan 01 00:30:30 IST 3921
Date Time format with kk : 24:30:30
Date Time format with HH : 00:30:30
Date Time format with hh : 12:30:30 AM
 

We've taken hours value in the input is 00 means early morning.

But from the above output, you can see the difference clearly that kk printed hours value as 24, HH is taken as 11 and HH is 12 with AM.

Use the right one based on your need otherwise it will change the date time values completely.

4. Conclusion

In this article, we've seen what are the differences among kk, HH and hh date formats and example program with SimpleDateFormat.

GitHub

Ref

How to display time in 24 hours format in java ?

No comments:

Post a Comment

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