Question: How can I format a duration in seconds using a pattern like H:MM:SS in Java? Existing Java utilities are geared towards formatting time, not durations.
Solution:
To format a duration without introducing external libraries, one can utilize Java's built-in Formatter class or similar shortcuts.
For example, given an integer representing the number of seconds s:
String formattedDuration = String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));
In this code:
The d format specifiers ensure that the minutes and seconds are always formatted with two digits, adding leading zeros as needed.
The above is the detailed content of How to Format a Duration in Seconds as H:MM:SS in Java?. For more information, please follow other related articles on the PHP Chinese website!