The answer by talex is correct that you should use a Duration
for this. In Java 9 formatting the Duration
has become a bit easier and more straightforward to write and read:
public static String formatDuration(long totalTimeMillis) {
Duration totalDuration = Duration.ofMillis(totalTimeMillis);
return String.format(Locale.ENGLISH,
"%02d hours %02d minutes",
totalDuration.toHours(),
totalDuration.toMinutesPart());
}
We no longer need the modulo operation (or similar) for finding the minutes. To demonstrate I called the above method using your time values from the question:
System.out.println(formatDuration(60300000));
System.out.println(formatDuration(63900000));
System.out.println(formatDuration(108000000));
System.out.println(formatDuration(117000000));
System.out.println(formatDuration(193500000));
It prints the results you asked for:
16 hours 45 minutes
17 hours 45 minutes
30 hours 00 minutes
32 hours 30 minutes
53 hours 45 minutes
I have put in a space between the number and the unit, I find it more readable that way, you can just remove it if you don’t want it.
The %02d
specifier in the format string makes sure you get two digits with a leading zero as necessary as in the question: formatDuration(14700000)
, for example yields 04 hours 05 minutes
.
SimpleDateFormat
was meant for formatting a date and/or a time of day, not a duration or elapsed time. I say “was” because that class is now long outdated, and since it was also notoriously troublesome I recommend you never use it again. For formatting a date or hour of day use a DateTimeFormatter
from java.time
.