public static String formatChronometer(long seconds) {
Duration dur = Duration.ofSeconds(seconds);
return String.format("%02d:%02d", dur.toMinutes(), dur.toSecondsPart());
}
When I fed 36005
into this method, it returned 600:05
.
I take it that your chronometer seconds denote a duration, an amount of time. Either an elapsed time or a value to count down from. Not a time of day (you mentioned 100 hours an example, but the time of day is never 100 hours). In that case I would clearly use the Duration
class for modelling it. It’s the most correct thing to do. Some use the word self-documenting about code written with such a consideration in mind.
The Duration.toSecondsPart
method was only introduced in Java 9. If you are using Java 8 (or Java 6 or 7 with the ThreeTen Backport), get the seconds part by subtracting the minutes and then converting to seconds:
long minutes = dur.toMinutes();
dur = dur.minusMinutes(minutes);
return String.format("%02d:%02d", minutes, dur.toSeconds());
Then the result is the same.
PS If your seconds denoted a time-of-day instead, the correct and self-documenting solution would be to use the LocalTime
class:
LocalTime chrono = LocalTime.ofSecondOfDay(seconds);
return String.format("%02d:%02d",
chrono.get(ChronoField.MINUTE_OF_DAY), chrono.getSecond());
This will reject seconds values greater than 86399
with an exception since the time of day cannot be 24:00
or greater.