Issue
I'd like to format a duration in seconds using a pattern like H:MM:SS. The current utilities in java are designed to format a time but not a duration.
Solution
If you're using a version of Java prior to 8... you can use Joda Time and PeriodFormatter
. If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using Duration
for the most part - you can then call toPeriod
(specifying whatever PeriodType
you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a Period
which you can format.
If you're using Java 8 or later: I'd normally suggest using java.time.Duration
to represent the duration. You can then call getSeconds()
or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a single negative sign in the output string. So something like:
public static String formatDuration(Duration duration) {
long seconds = duration.getSeconds();
long absSeconds = Math.abs(seconds);
String positive = String.format(
"%d:%02d:%02d",
absSeconds / 3600,
(absSeconds % 3600) / 60,
absSeconds % 60);
return seconds < 0 ? "-" + positive : positive;
}
Formatting this way is reasonably simple, if annoyingly manual. For parsing it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.
Answered By - Jon Skeet
Answer Checked By - Katrina (JavaFixing Volunteer)