Hour Format Example

This example shows how to format hour using Format class. In this program we use a pattern of special characters to time format.

Hour Format Example

This example shows how to format hour using Format class. In this program we use a pattern of special characters to time format.

Hour Format Example

Hour Format Example

     

This example shows how to format hour using Format class. In this program we use a pattern of special characters to time format.

Description of the code :

SimpleDateFormat() : SimpleDateFormat class use for formatting and parsing dates. It allows for formatting date into text , parsing text into date and normalization.

format() : This method is used for format Date class object into date / time and appends the it into the StringBuffer.

HourFormat.java

import java.text.*;
import java.util.*;

public class HourFormat {

  public static void main(String args[]) {

  String s;
  Format formatter;
  Date date = new Date();

  // The hour (1-12)
  formatter = new SimpleDateFormat("h")// 8
  s = formatter.format(date);
  System.out.println("The hour (1-12) : " + s);

  formatter = new SimpleDateFormat("hh");  // 08
  s = formatter.format(date);
  System.out.println("The hour (1-12) : " + s);

  // The hour (0-23)
  formatter = new SimpleDateFormat("H")// 8
  s = formatter.format(date);
  System.out.println("The hour (0-23) : " + s);

  formatter = new SimpleDateFormat("HH");  // 08
  s = formatter.format(date);
  System.out.println("The hour (0-23) : " + s);
  }
}

Output:
The hour (1-123
The hour (1-1203
The hour (0-2315
The hour (0-2315

Download code