Reputation: 777
I am using the following code to display a timer in my app (in an editText named "time")
final TextView time = (TextView) findViewById(R.id.txtTime);
Long spentTime = System.currentTimeMillis() - startTime;
Long minius = (spentTime/1000)/60;
Long seconds = (spentTime/1000) % 60;
time.setText(minius+":"+seconds);
handler.postDelayed(this, 1000);
This works well but the formatting is a bit ugly. So for e.g. at 4 seconds the timer shows "0:4" which doesn't really look like a timer.
How do I change the formatting of the setText so that it shows a more usual timer (such as 00:04), without having to make a bunch of if statements (if seconds less than 10 then 0+seconds and so on)
Upvotes: 0
Views: 226
Reputation: 3036
You need to set leading 0's with the String.format
command. Try:
time.setText(String.format("%02d",minius) + ":" + String.format("%02d",seconds));
That gives always gives you two digits leading with a 0 when it is only one.
Upvotes: 0
Reputation: 159844
You can use String.format
to pad the digits with 0
's:
String formattedTime = String.format("%02d:%02d", minius, seconds);
time.setText(formattedTime);
Upvotes: 1