Skip to Content

Formatting hour using SimpleDateFormat

  1. /*
  2.   Formatting hour using SimpleDateFormat
  3.   This example shows how to format hour field using Java SimpleDateFormat class.
  4.   Hour can be formatted in H, HH, h, hh, k, kk, K and KK formats.  
  5. */
  6.  
  7. import java.text.SimpleDateFormat;
  8. import java.util.Date;
  9.  
  10. public class FormattingHour {
  11.  
  12.   public static void main(String[] args) {
  13.  
  14.     //create Date object
  15.     Date date = new Date();
  16.    
  17.      //formatting hour in h (1-12 in AM/PM) format like 1, 2..12.
  18.      String strDateFormat = "h";
  19.      SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
  20.      
  21.      System.out.println("hour in h format : " + sdf.format(date));
  22.      
  23.      //formatting hour in hh (01-12 in AM/PM) format like 01, 02..12.
  24.      strDateFormat = "hh";
  25.      sdf = new SimpleDateFormat(strDateFormat);
  26.      
  27.      System.out.println("hour in hh format : " + sdf.format(date));
  28.  
  29.      //formatting hour in H (0-23) format like 0, 1...23.
  30.      strDateFormat = "H";
  31.      sdf = new SimpleDateFormat(strDateFormat);
  32.      
  33.      System.out.println("hour in H format : " + sdf.format(date));
  34.  
  35.      //formatting hour in HH (00-23) format like 00, 01..23.
  36.      strDateFormat = "HH";
  37.      sdf = new SimpleDateFormat(strDateFormat);
  38.      
  39.      System.out.println("hour in HH format : " + sdf.format(date));
  40.  
  41.      //formatting hour in k (1-24) format like 1, 2..24.
  42.      strDateFormat = "k";
  43.      sdf = new SimpleDateFormat(strDateFormat);
  44.      
  45.      System.out.println("hour in k format : " + sdf.format(date));
  46.  
  47.      //formatting hour in kk (01-24) format like 01, 02..24.
  48.      strDateFormat = "kk";
  49.      sdf = new SimpleDateFormat(strDateFormat);
  50.      
  51.      System.out.println("hour in kk format : " + sdf.format(date));
  52.  
  53.      //formatting hour in K (0-11 in AM/PM) format like 0, 1..11.
  54.      strDateFormat = "K";
  55.      sdf = new SimpleDateFormat(strDateFormat);
  56.      
  57.      System.out.println("hour in K format : " + sdf.format(date));
  58.  
  59.      //formatting hour in KK (00-11) format like 00, 01,..11.
  60.      strDateFormat = "KK";
  61.      sdf = new SimpleDateFormat(strDateFormat);
  62.      
  63.      System.out.println("hour in KK format : " + sdf.format(date));
  64.    
  65.   }
  66.  
  67. }
  68.  
  69. /*
  70. Typical output would be
  71. hour in h format : 12
  72. hour in hh format : 12
  73. hour in H format : 0
  74. hour in HH format : 00
  75. hour in k format : 24
  76. hour in kk format : 24
  77. hour in K format : 0
  78. hour in KK format : 00
  79. */