Question

I have current date in format "2014-05-14T16:23:11.810Z" and Counter date is "2014-05-15T16:24:13.810Z"

I want to display the counter time in between those dates in HH:MM:SS i.e 24:01:02 in TextView which update continuously by 1 sec. Like timer

but how to calculate the difference between these two dates and convert it into HH:MM:SS

I writting simple code which countdown timer shows in milliseconds in android :

CountDownTimer timer=new CountDownTimer(300000, 1000) {
        public void onTick(long millisUntilFinished) {
            txtNewBetTimer.setText(""+millisUntilFinished / 1000);
        }

        public void onFinish() {
            txtNewBetTimer.setText("Time Up");
        }
    };
    timer.start();

I want output like this :

enter image description here

Please anyone help me for this ...

Thanks in advance..

Was it helpful?

Solution

// try this way,hope this will help you...

CountDownTimer timer=new CountDownTimer(300000, 1000) {
   public void onTick(long millisUntilFinished) {
        txtNewBetTimer.setText(""+String.format("%d:%d:%d",
        TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
        toMinutes(millisUntilFinished))));
   }

   public void onFinish() {
        txtNewBetTimer.setText("Time Up");
   }
};
timer.start();

Alternative way

CountDownTimer timer=new CountDownTimer(300000, 1000) {
   public void onTick(long millisUntilFinished) {
         int seconds = (int) (millisUntilFinished / 1000) % 60 ;
         int minutes = (int) ((millisUntilFinished / (1000*60)) % 60);
         int hours   = (int) ((millisUntilFinished / (1000*60*60)) % 24);
         txtNewBetTimer.setText(String.format("%d:%d:%d",hours,minutes,seconds));
   }
   public void onFinish() {
         txtNewBetTimer.setText("Time Up");
   }
};
timer.start();    

OTHER TIPS

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = new Date(); 

public void onTick(long millisUntilFinished) {
    date.setTime(millisUntilFinished);
    textView.setText(sdf.format(date));
}

You can code it yourself or use the provided utility method DateUtils.formatElapsedTime().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top