1

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...?

heisenbergman
  • 1,459
  • 4
  • 16
  • 33
  • 1
    [PrettyTime](http://ocpsoft.org/prettytime/) *might* be able to help – MadProgrammer Jul 11 '13 at 01:03
  • 1
    possible duplicate of [How to convert Milliseconds to "X mins, x seconds" in Java?](http://stackoverflow.com/questions/625433/how-to-convert-milliseconds-to-x-mins-x-seconds-in-java) – andrewdotn Jul 11 '13 at 01:08

2 Answers2

1

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);
}
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • Thanks! I eventually used this code: `long currTime = System.currentTimeMillis() - startLevel; long tenths = (currTime + 50) / 100; // round long seconds = tenths / 10; long minutes = seconds / 60; String timeMS = String.format("%1$02d:%2$02d.%3$01d", minutes, seconds % 60, tenths % 10);` – heisenbergman Jul 11 '13 at 01:38
1

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

Community
  • 1
  • 1
anttix
  • 7,709
  • 1
  • 24
  • 25