How to format an elapsed time interval in hh:mm:ss.SSS format in Java?
Support for what you want to do is built in to the latest JDKs with a little known class called TimeUnit
.
What you want to use is java.util.concurrent.TimeUnit to work with intervals.
SimpleDateFormat
does just what it sounds like it does, it formats instances of java.util.Date
, or in your case it converts the long
value into the context of a java.util.Date
and it doesn't know what to do with intervals which is what you apparently are working with.
You can easily do this without having to resort to external libraries like JodaTime.
import java.util.concurrent.TimeUnit;
public class Main
{
private static String formatInterval(final long l)
{
final long hr = TimeUnit.MILLISECONDS.toHours(l);
final long min = TimeUnit.MILLISECONDS.toMinutes(l - TimeUnit.HOURS.toMillis(hr));
final long sec = TimeUnit.MILLISECONDS.toSeconds(l - TimeUnit.HOURS.toMillis(hr) - TimeUnit.MINUTES.toMillis(min));
final long ms = TimeUnit.MILLISECONDS.toMillis(l - TimeUnit.HOURS.toMillis(hr) - TimeUnit.MINUTES.toMillis(min) - TimeUnit.SECONDS.toMillis(sec));
return String.format("%02d:%02d:%02d.%03d", hr, min, sec, ms);
}
public static void main(final String[] args)
{
System.out.println(formatInterval(Long.parseLong(args[0])));
}
}
The output will be formatted something like this
13:00:00.000
A shorter way to do this is to use the DurationFormatUtils class in Apache Commons Lang:
public static String formatTime(long millis) {
return DurationFormatUtils.formatDuration(millis, "HH:mm:ss.S");
}
Why not this ?
public static String GetFormattedInterval(final long ms) {
long millis = ms % 1000;
long x = ms / 1000;
long seconds = x % 60;
x /= 60;
long minutes = x % 60;
x /= 60;
long hours = x % 24;
return String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, millis);
}