tl;dr
Duration.ofSeconds ( 7_325L ).toString()
PT2H2M5S
Details
The Answer by DimaSan is correct, addressing the math issue.
FYI, the java.time classes can do this math work for you.
ISO 8601
Also, tracking a span of time as a String in the format of hh:mm:ss
is not recommended. That format creates ambiguity as it looks like a time-of-day. The ISO 8601 standard defines many sensible unambiguous formats for date-time values. The one for a span of time not attached to the timeline is known as durations: PnYnMnDTnHnMnS
. The P
marks the beginning, the T
separates years-month-days from hours-minutes-seconds. For example, "P3Y6M4DT12H30M5S" represents a duration of "three years, six months, four days, twelve hours, thirty minutes, and five seconds". One and a half minutes is PT1M30S
.
The java.time classes use ISO 8601 formats by default when parsing/generating Strings.
java.time.Duration
The Duration
class in java.time represents a span of time as a total number of seconds and of a fractional second as nanoseconds.
Duration d = Duration.ofSeconds( 3_719L );
String output = d.toString();
PT1H1M59S
Next, a larger number.
Duration d = Duration.ofSeconds ( 7_325L );
PT2H2M5S
In Java 8 this class inexplicably lacks getter methods for the various parts such as the number of hours and the number of minutes and the number of seconds. Remedied in Java 9 with the addition of getPart
methods.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.