user2694368
user2694368

Reputation: 33

Format countdown timer to use a leading zero digit when less than ten seconds

My countdown timer needs to display seconds in the correct format. It is currently all correct, until it gets to counts less than 10 seconds.

At that point it displays as follows: 9 8 7 6 5 4 3 2 1. I need it in the format of 09 08 06 05 04 03 02 01.

Here is the timers code:

private CountDownTimer timer(int time)
{
    CountDownTimer a = new CountDownTimer(time, 1000) 
    {
        public void onTick(long millisUntilFinished) {
            String clock;
            clock = "" + ((millisUntilFinished / 1000)/60)%60 + ":" + ((millisUntilFinished / 1000)%60);
            Clk.setText(clock);
            // mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
        }

        public void onFinish() {
            alarm.start();
            Clk.setText("00:00");
        }
    }.start();

    return a;
}

Upvotes: 1

Views: 1858

Answers (5)

Gene
Gene

Reputation: 11267

int minutes = 15;
int seconds = 1;
String display = String.format("%02d:%02d", minutes, secconds);
System.out.println("display= " + display)

Upvotes: 1

Roland Illig
Roland Illig

Reputation: 41625

int seconds = millisUntilFinished / 1000;
Clk.setClock(String.format("%02d:%02d", seconds / 60, seconds % 60));

This will display:

12:34
07:45
00:10
00:09
00:00

Upvotes: 2

sam
sam

Reputation: 2486

clock = "" + (String.format("%02d",(millisUntilFinished / 1000)/60)%60) + ":" + (String.format("%02d",((millisUntilFinished / 1000)%60));

            Clk.setText(clock);

Use

String.format("%02d",9) //provides 09

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44834

Try using String.format

int remaining = ((millisUntilFinished / 1000)%60);
clock = String.format("seconds remaining: %02d .", remaining);

Upvotes: 3

Apoorv
Apoorv

Reputation: 13520

Check if the seconds you receive have value less than 10 if so append 0 in front of them while doing setText like

if((millisUntilFinished / 1000) % 60 < 10)
    clock = "" + ((millisUntilFinished / 1000)/60)%60 + ":0" + ((millisUntilFinished / 1000)%60);
else
    clock = "" + ((millisUntilFinished / 1000)/60)%60 + ":" + ((millisUntilFinished / 1000)%60);

Upvotes: 1

Related Questions