heisenbergman
heisenbergman

Reputation: 1449

How can I convert elapsed milliseconds stored in a long to a String formatted to mm:ss.ss in Java?

I have a variable currTime computed in the following way:

long currTime = System.currentTimeMillis() - start; //where start is the start time of whatever I'm timing

How do I convert this to a String for display such that for example:

12544 will display as "00:12.54"

67855 will display as "01:07.86"

...so on and so forth...?

Upvotes: 1

Views: 1306

Answers (2)

anttix
anttix

Reputation: 7779

A solution for three digit milliseconds is very easy:

public String formatDuration(long elapsedTimeMillis) {
    SimpleDateFormat df = new java.text.SimpleDateFormat("mm:ss.SSS");
    df.setTimeZone(TimeZone.getTimeZone("UTC")); // Epoch is UTC
    return df.format(new Date(elapsedTimeMillis));
}

For two digit milliseconds, one has to use Joda Time formatter, remove the final digit from the string or go for a manual solution.

See: Java DateFormat for 2 millisecond precision

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

The easiest, I think, is to do it by hand:

public String elapsedToString(long elapsedTimeMillis) {
    long seconds = (elapsedTimeMillis + 500) / 1000; // round
    long minutes = seconds / 60;
    long hours = minutes / 60;
    return String.format("%1$02d:%2$02d:%3$02d",
        hours,
        minutes % 60,
        seconds % 60);
}

Oops. You wanted mm:ss.ss

public String elapsedToString(long elapsedTimeMillis) {
    long hundredths = (elapsedTimeMillis + 5) / 10; // round
    long seconds = hundredths / 100;
    long minutes = seconds / 60;
    return String.format("%1$02d:%2$02d.%3$02d",
        minutes,
        seconds % 60,
        hundredths % 100);
}

Upvotes: 1

Related Questions