How to Format Seconds in Java?
Last Updated :
08 Feb, 2024
In Java, when working with time-related data, we may need to format seconds to make it a more human-readable representation. In this article, we will see how to format seconds in Java.
Example of
Input: long seconds = 3665;
Output: Formatted Time: 1 hour, 1 minute and 5 seconds
Syntax
The formatting can be achieved using Duration and Period classes from java.time package introduced in Java 8.
String formattedTime = Duration.ofSeconds(seconds)
.toString()
.substring(2)
.replaceAll("(\\d[HMS])(?!$)", "$1 ")
.toLowerCase();
Program to Format Seconds in Java
Below is the implementation of Format Seconds in Java:
Java
import java.io.*;
import java.time.Duration;
public class GFG {
public static String Seconds( long seconds) {
return Duration.ofSeconds(seconds)
.toString()
.substring( 2 )
.replaceAll( "(\\d[HMS])(?!$)" , "$1 " )
.toLowerCase();
}
public static void main(String[] args) {
long seconds = 3665 ;
String formattedTime = Seconds(seconds);
System.out.println( "Formatted Time: " + formattedTime);
}
}
|
Output
Formatted Time: 1h 1m 5s
Explanation of the Program:
In the above program,
- Duration.ofSeconds(seconds): Creates a Duration object representing the given duration in the seconds.
- toString(): Converts the Duration object to its string representation.
- substring(2): The Removes the leading “PT” (Period of Time) from string.
- replaceAll(“(\d[HMS])(?!$)”, “$1 “): Adds a space between the numeric value and unit (H, M or S) to improve readability.
- toLowerCase(): Converts the string to lowercase for the consistent format.
Share your thoughts in the comments
Please Login to comment...