Home >Java >javaTutorial >How to Format a Duration in H:MM:SS Format in Java?
Formatting Durations in Java (H:MM:SS)
Question:
How can I format a duration, represented in seconds, in the H:MM:SS format in Java?
Answer:
To format a duration using the H:MM:SS pattern, you can use the following approach:
Create a Formatter object: This object will handle the formatting of the duration.
java.util.Formatter formatter = new java.util.Formatter();
Use the %d modifier: This modifier specifies that the variable should be formatted as a decimal integer.
formatter.format("%d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, (seconds % 60));
Retrieve the formatted string: Finally, retrieve the formatted duration by calling the toString() method on the formatter object.
String formattedDuration = formatter.toString();
Example:
int seconds = 3661; String formattedDuration = String.format("%d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, (seconds % 60)); System.out.println(formattedDuration); // Output: 1:01:01
The above is the detailed content of How to Format a Duration in H:MM:SS Format in Java?. For more information, please follow other related articles on the PHP Chinese website!