Java Program to format time using Custom Format


Firstly, set the time with SimpleDateFormat class

Format dateFormat = new SimpleDateFormat("h:m:s");

Now, for custom format, let us fetch the hour, minute and second individually

Hour

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

Minute

// minute
dateFormat = new SimpleDateFormat("m");
String strMinute = dateFormat.format(new Date());
System.out.println("Minute: "+strMinute);

Second

// second
dateFormat = new SimpleDateFormat("s");
String strSecond = dateFormat.format(new Date());
System.out.println("Second: "+strSecond);

The following is an example −

Example

 Live Demo

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
   public static void main(String[] argv) throws Exception {
      Format dateFormat = new SimpleDateFormat("h:m:s");
      String str = dateFormat.format(new Date());
      System.out.println("Time: "+str);
      // hour
      dateFormat = new SimpleDateFormat("h");
      String strHour = dateFormat.format(new Date());
      System.out.println("Hour: "+strHour);
      // minute
      dateFormat = new SimpleDateFormat("m");
      String strMinute = dateFormat.format(new Date());
      System.out.println("Minute: "+strMinute);
      // second
      dateFormat = new SimpleDateFormat("s");
      String strSecond = dateFormat.format(new Date());
      System.out.println("Second: "+strSecond);
   }
}

Output

Time: 10:58:52
Hour: 10
Minute: 58
Second: 52

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 27-Jun-2020

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements