Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

How to Format Seconds in Java



Formatting seconds can be done by using the SimpleDateFormat class in Java. By specifying the pattern "ss", you can extract and display the seconds in a specific format.

Formatting Seconds Using SimpleDateFormat

SimpleDateFormat: SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.

Date class: The Java Util Date class represents a specific instant in time, with millisecond precision.

Steps

  • 1. Create a Date object: Initializes a Date object that captures the current date and time.

Date date = new Date();
  • 2. Define the seconds format: Creates a SimpleDateFormat object sdf with the pattern "ss" to format the seconds.

SimpleDateFormat sdf = new SimpleDateFormat("ss");
  • 3. Format the seconds: Uses the format method of sdf to extract and format the seconds from the current date.

sdf.format(date);

Java program to format seconds

The following example formats the second by using SimpleDateFormat('ss') constructor and sdf.format(date) method of SimpleDateFormat class

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main{
   public static void main(String[] args) {
      Date date = new Date();
      SimpleDateFormat sdf = new SimpleDateFormat("ss");
      System.out.println("seconds in ss format : " + sdf.format(date));
   }
}

Output

seconds in ss format : 14

Explanation

The program uses the Date class to get the current date and time. It then creates a SimpleDateFormat object with the pattern "ss", which formats the seconds as two digits. The format() method is used to get the seconds from the current time, and the result is printed. If the current seconds are 14, the output will be "Seconds in ss format: 14". This ensures that the seconds are always displayed as two digits, even if they are less than 10 (like "09" instead of "9").

java_date_time.htm
Advertisements