Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display minutes and seconds in countdowntimer

Tags:

android

I need some help. I cannot be able to display the number for minutes correctly as it give 0 instead of the number I desire but the second work fine. Here is my code:

new CountDownTimer(90000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            tvTime.setText("Time remaining: " + String.format("%d min: %d sec",
                    TimeUnit.MICROSECONDS.toMinutes( millisUntilFinished),
                    TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
        }
 });

I want it to display in 1 min:30 sec instead of 0 min:30 sec at the start of the countdown.

like image 871
Mobile Developer Avatar asked Jan 11 '17 10:01

Mobile Developer


3 Answers

Try this

String text = String.format(Locale.getDefault(), "Time Remaining %02d min: %02d sec", 
              TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60, 
              TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
tvTime.setText(text);
like image 66
Deepak Goyal Avatar answered Oct 03 '22 08:10

Deepak Goyal


## Try this one ##

private void startTimer(int noOfMinutes) {
CountDownTimer  countDownTimer = new CountDownTimer(noOfMinutes, 1000) {
        public void onTick(long millisUntilFinished) {
            long millis = millisUntilFinished;
            //Convert milliseconds into hour,minute and seconds
            String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
            countdownTimerText.setText(hms);//set text
        }
        public void onFinish() {
            countdownTimerText.setText("TIME'S UP!!"); //On finish change timer text
        }
    }.start();

}
like image 25
Dheeraj Kumar Avatar answered Oct 03 '22 08:10

Dheeraj Kumar


int secondsUntilFinished = milisUntilFinished / 1000;

int seconds = secondsUntilFinished % 60;
int mins = secondsUntilFinished / 60;
like image 41
user2310252 Avatar answered Oct 03 '22 07:10

user2310252