0

I've made a quick timer and I'm trying to display the time in the format "00:00.00" where the first 00 is the minutes and the 00.00 is the seconds and fraction of seconds. I have the below format code:

// Get the delta time
long timeDelta = System.currentTimeMillis()-startTimeMillis;

int minutes;
double seconds;

// Now split
if( timeDelta>60000 ) { // Minutes
    minutes = (int)(timeDelta/60000);
    timeDelta-= minutes*60000;
}
else
    minutes = 0;

// Now for the rest
seconds = timeDelta/1000.0;

// Get the text string
final String timeString = String.format( "%1$02d:%2$02.2f", minutes, seconds );

But the string keeps coming out like "00:6.42" instead of "00:06.42". How can I get String.format to format the decimal with leading zeroes and the decimal places?

Mikey A. Leonetti
  • 2,834
  • 3
  • 22
  • 36

1 Answers1

2

A better way to do that in Java is to use SimpleDateFormatlike this :

long timeDelta = System.currentTimeMillis()-startTimeMillis;

SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("mm:ss:SS");
System.out.println(simpleDateFormat.format(timeDelta));

Working example

Ashish Ranjan
  • 5,523
  • 2
  • 18
  • 39
  • Hello. Thank you for your post. The issue to this comes in if the number of minutes elapsed is greater than 59. It will wrap again to 0 I'm assuming since it's a time formatter. It would be nice to keep counting up the minutes. – Mikey A. Leonetti Jun 30 '16 at 15:47
  • yeah that makes sense, so my previous edit will work in that case. – Ashish Ranjan Jun 30 '16 at 15:49
  • you can use `TimeUnit.MILLISECONDS` in that case as demonstrated here : http://stackoverflow.com/questions/9027317/how-to-convert-milliseconds-to-hhmmss-format – Ashish Ranjan Jun 30 '16 at 15:53