Display hour with SimpleDateFormat(“hh”) in Java

Java 8Object Oriented ProgrammingProgramming

To work with SimpleDateFormat class in Java, import the following package.

import java.text.SimpleDateFormat;

Now, set the format with SimpleDateFormat(“hh”) to display hour −

Format f = new SimpleDateFormat("hh");

Now, get the hour in a string −

String strHour = f.format(new Date());

The following is an example −

Example

 Live Demo

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) throws Exception {
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s");
      System.out.println("Today's date = "+simpleformat.format(cal.getTime()));
      Format f = new SimpleDateFormat("hh");
      String strHour = f.format(new Date());
      System.out.println("Current Hour = "+strHour);
   }
}

Output

Today's date = 26/December/2018 06:25:32
Current Hour = 06
raja
Published on 26-Dec-2018 07:27:15
Advertisements