Java SimpleDateFormat format hour as "1", "01"

Description

Java SimpleDateFormat format hour as "1", "01"


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

public class Main {

  public static void main(String[] args) {
    // create Date object
    Date date = new Date();

    // formatting hour in h (1-12 in AM/PM) format like 1, 2..12.

    SimpleDateFormat sdf = new SimpleDateFormat("h");

    System.out.println("hour in h format : " + sdf.format(date));

    // formatting hour in hh (01-12 in AM/PM) format like 01, 02..12.

    sdf = new SimpleDateFormat("hh");

    System.out.println("hour in hh format : " + sdf.format(date));

    // formatting hour in H (0-23) format like 0, 1...23.

    sdf = new SimpleDateFormat("H");

    System.out.println("hour in H format : " + sdf.format(date));

    // formatting hour in HH (00-23) format like 00, 01..23.

    sdf = new SimpleDateFormat("HH");

    System.out.println("hour in HH format : " + sdf.format(date));

    // formatting hour in k (1-24) format like 1, 2..24.

    sdf = new SimpleDateFormat("k");

    System.out.println("hour in k format : " + sdf.format(date));

    // formatting hour in kk (01-24) format like 01, 02..24.
    sdf = new SimpleDateFormat("kk");

    System.out.println("hour in kk format : " + sdf.format(date));

    // formatting hour in K (0-11 in AM/PM) format like 0, 1..11.
    sdf = new SimpleDateFormat("K");

    System.out.println("hour in K format : " + sdf.format(date));

    // formatting hour in KK (00-11) format like 00, 01,..11.
    sdf = new SimpleDateFormat("KK");

    System.out.println("hour in KK format : " + sdf.format(date));

  }//from w  w w . j  ava2 s.  c  o  m

}



PreviousNext

Related