Display seconds with SimpleDateFormat('ss') 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(“ss”) to display seconds in two-digit.

Format f = new SimpleDateFormat(”ss”);

Now, get the seconds in a string −

String strSeconds = 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 {
      // displaying current date and time
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s");
      System.out.println("Today's date = "+simpleformat.format(cal.getTime()));
      // displaying hour
      Format f = new SimpleDateFormat("H");
      String strHour = f.format(new Date());
      System.out.println("Current Hour = "+strHour);
      // displaying minutes
      f = new SimpleDateFormat("mm");
      String strMinute = f.format(new Date());
      System.out.println("Current Minutes = "+strMinute);
      // displaying seconds in two-digits
      f = new SimpleDateFormat("ss");
      String strSeconds = f.format(new Date());
      System.out.println("Current Seconds = "+strSeconds);
   }
}

Output

Today's date = 26/November/2018 08:06:42
Current Hour = 8
Current Minutes = 06
Current Seconds = 42
raja
Published on 26-Dec-2018 14:40:12
Advertisements