Formatting Durations in Java: A Practical Approach to Achieve H:MM:SS
When working with durations, whether in seconds or other units, it's often desirable to display the time elapsed in a user-friendly format like H:MM:SS. However, standard Java utilities are typically designed for formatting dates and times, not durations explicitly.
Solution:
Overriding this limitation in Java requires a customized approach. Here's a simple and effective solution using the Formatter class:
String formatDuration(int seconds) { return String.format("%d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, seconds % 60); }
This short method takes an integer representing the duration in seconds and returns a formatted string following the H:MM:SS pattern.
Implementation:
Example:
To format a duration of 36061 seconds:
System.out.println(formatDuration(36061)); // Output: 10:01:01
This method provides a concise and efficient way to format durations in Java applications, enabling developers to display elapsed time in a human-readable format.
The above is the detailed content of How Can I Format Durations in Java as H:MM:SS?. For more information, please follow other related articles on the PHP Chinese website!