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?
Answer
A better way to do that in Java is to use SimpleDateFormat
like this :
long timeDelta = System.currentTimeMillis()-startTimeMillis; SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("mm:ss:SS"); System.out.println(simpleDateFormat.format(timeDelta));