Program to Format Seconds in Java
Below is the implementation of Format Seconds in Java:
Java
// Java program to format seconds import java.io.*; import java.time.Duration; public class GFG { // method to format seconds into HH:MM:SS public static String Seconds( long seconds) { // convert seconds to Duration object and format it return Duration.ofSeconds(seconds) .toString() // convert to string .substring( 2 ) // remove "PT" prefix .replaceAll( "(\\d[HMS])(?!$)" , "$1 " ) // add space between values .toLowerCase(); // convert to lowercase } public static void main(String[] args) { // test the Seconds method long seconds = 3665 ; String formattedTime = Seconds(seconds); System.out.println( "Formatted Time: " + formattedTime); } } |
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.
How to Format Seconds in Java?
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();