Search code examples
androidtimecountdownseconds

CountDownTimer seconds in XX format


I have a CountDownTimer like that:

                     public void onTick(long millisUntilFinished) {                      
                             tv1.setText(""+String.format("%d:%d", 
                                        TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished),
                                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - 
                                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));  
                     }`

But at seconds less than 10 the textview should display the second letter with a zero. So that it will look like "1:02" and not like "1:2".


Solution

  • Partially from the Android Formatter docs, "pad the number with leading zeros", which requires you to specify width:

    In the format string, your target width is 2. To pad with 0's you prepend a 0 to that for your decimal numbers (d), yielding:

    String.format("%02d:%02d", decimal1, decimal2) ...