How to Format Hours Using Java SimpleDateFormat


In this example, we will learn how to format hour field with Java SimpleDateFormat class. In programming, hours can be formatted in the formats including H, HH, h, hh, k, kk, K and KK.
Below shows how they differ:

  • H: (0-23) will look like 0, 1, 2..23.
  • HH: (00-23) will look like 00, 01..23
  • h: (1-12 in AM/PM) will look like 1, 2, 3..12.
  • hh: (01-12 in AM/PM) will look like 01, 02, 03..12.
  • k: (1-24) will look like 1, 2, 3..24.
  • kk: (01-24) will look like 01, 02, 03..24.
  • K: (0-11 in AM/PM) will look like 0, 1, 2, 3..11.
  • KK: (00-11 in AM/PM) will look like 01, 02, 03..11.

Source Code

package com.beginner.examples;

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

public class FormattingHour {

	public static void main(String[] args) {
		
		//create Date.
		Date date = new Date();
		
		System.out.println("Before formatting , date is : " + date);
		
		/*
		 * To format hour in h (1-12 in AM/PM) use SimpleDateFormat("h") Constructor.
		 */
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h");
		System.out.println("Hour in h format : " + simpleDateFormat.format(date));
		
		/*
		 * To format hour in hh (01-12 in AM/PM) use SimpleDateFormat("hh") Constructor.
		 */
		simpleDateFormat = new SimpleDateFormat("hh");
		System.out.println("Hour in hh format : " + simpleDateFormat.format(date));
		
		/*
		 * To format hour in H (0-23) use SimpleDateFormat("H") Constructor.
		 */
		simpleDateFormat = new SimpleDateFormat("H");
		System.out.println("Hour in H format : " + simpleDateFormat.format(date));
		
		/*
		 * To format hour in HH (00-23) use SimpleDateFormat("H") Constructor.
		 */
		simpleDateFormat = new SimpleDateFormat("HH");
		System.out.println("Hour in HH format : " + simpleDateFormat.format(date));
		
	}
}

Output:

Before formatting , date is : Fri Jun 14 14:16:18 CST 2019
hour in h format : 2
hour in hh format : 02
hour in H format : 14
hour in HH format : 14

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments