views:

216

answers:

4

I'm familiar with printing time difference in milliseconds:

 long time = System.currentTimeMillis();
 //do something that takes some time...
 long completedIn = System.currentTimeMillis() - time;

But, is there a nice way print a complete time in a specified format (eg: HH:MM:SS) either using Apache Commons or even the dreaded platform API's Date/Time objects? In other words, what is the shortest, simplest, no nonsense way to write a time format derived from milliseconds in Java?

+1  A: 

If you actually want to see a millisecond difference, I don't think there's a shorter, simpler way.

If you need a more powerful (but certainly not simpler) way to collect performance statistics, there is Perf4J.

Michael Borgwardt
+1  A: 

Not to my knowledge. But printf() can do this easily if you calculate the values for H, M and S, and use a %02 pattern for each.

Thorbjørn Ravn Andersen
+5  A: 

Apache Commons has the DurationFormatUtils class for applying a specified format to a time duration. So, something like:

long time = System.currentTimeMillis();
//do something that takes some time...
long completedIn = System.currentTimeMillis() - time;

DurationFormatUtils.formatDuration(completedIn, "HH:mm:ss:SS");
Bill the Lizard
You could even inline that to:DurationFormatUtils.formatDuration(System.currentTimeMillis() - time, "HH:mm:ss:SS");
Liggy
Or use the almost identical, built-in DurationFormatUtils.formatDurationHMS(end-start);
JRL
@JRL: `DurationFormatUtils.formatDurationHMS(end-start);` will satisfy the example given in the question, but I added the milliseconds in my solution.
Bill the Lizard
@Bill: yep! Although `formatDurationHMS` doesn't quite fit the requirements as it's `H:m:s` and not `HH:mm:ss`, but I just wanted to point it out as a possibility.
JRL
A: 

A library designed for the purpose is the better approach, but SimpleDateFormat with the right TimeZone may suffice for periods less than a day. Longer periods require treating the day specially.

import java.text.DateFormat;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

public class Elapsed {

    private static final long MS_DAY = 24 * 60 * 60 * 1000;
    private final DateFormat df = new SimpleDateFormat("HH : mm : ss : S");

    public Elapsed() {
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
    }

    private String format(long elapsed) {
        long day = elapsed / MS_DAY;
        StringBuilder sb = new StringBuilder();
        sb.append(day);
        sb.append(" : ");
        sb.append(df.format(new Date(elapsed)));
        return sb.toString();
    }

    public static void main(String[] args) {
        Elapsed e = new Elapsed();
        for (long t = 0; t < 3 * MS_DAY; t += MS_DAY / 2) {
            System.out.println(e.format(t));
        }
    }
}

Console output:

0 : 00 : 00 : 00 : 0
0 : 12 : 00 : 00 : 0
1 : 00 : 00 : 00 : 0
1 : 12 : 00 : 00 : 0
2 : 00 : 00 : 00 : 0
2 : 12 : 00 : 00 : 0
trashgod