Display hour in h (1-12 in AM/PM) format in Java

Java 8Object Oriented ProgrammingProgramming

The h format in Java Date is like 1-12 hour in AM/ PM. Use SimpleDateFormat("h") to get the same format;

// displaying hour in h format
SimpleDateFormat simpleformat = new SimpleDateFormat("h");
String strHour = simpleformat.format(new Date());
System.out.println("Hour in h format = "+strHour);

Above, we have used the SimpleDateFormat class, therefore the following package is imported −

import java.text.SimpleDateFormat;

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 {
      // displaying current date and time
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
      System.out.println("Today's date and time = "+simpleformat.format(cal.getTime()));
      // displaying date
      simpleformat = new SimpleDateFormat("dd/MMMM/yyyy");
      String str = simpleformat.format(new Date());
      System.out.println("Current Date = "+str);
      // current time
      simpleformat = new SimpleDateFormat("HH.mm.ss Z");
      String strTime = simpleformat.format(new Date());
      System.out.println("Current Time = "+strTime);
      // displaying hour in h format
      simpleformat = new SimpleDateFormat("h");
      String strHour = simpleformat.format(new Date());
      System.out.println("Hour in h format = "+strHour);
   }
}

Output

Today's date and time = Mon, 26 Nov 2018 09:52:22 +0000
Current Date = 26/November/2018
Current Time = 09.52.22 +0000
Hour in h format = 9
raja
Published on 26-Dec-2018 12:00:27
Advertisements