I make an Application where I need to obtain the remaining time for the day of an event, using the class CountDownTimer
I get a counter for days and dates but I can not think of how to get the remaining time.
For this I have two dates established by means of two Date
and I need to know the time remaining between them, for the date of the event I have the format:
Date(int year, int month, int day, int hour, int minute, int second);
And for the current time I simply generate a new date
Date date = new Date();
How can I get the remaining time in days, hours, minutes and seconds.
My code in which I only have the counter with the current time until the event:
First declare the variables:
private TextView countDown;
private CountDownTimer countDownTimer;
private long initialTime =
DateUtils.DAY_IN_MILLIS * 110 +
DateUtils.HOUR_IN_MILLIS * 9 +
DateUtils.MINUTE_IN_MILLIS * 3 +
DateUtils.SECOND_IN_MILLIS * 42;
and then handle it in CountDownTimer
:
countDownTimer = new CountDownTimer(initialTime, 1000) {
StringBuilder time = new StringBuilder();
@Override
public void onTick(long millisUntilFinished) {
time.setLength(0);
// Use days if appropriate
if(millisUntilFinished > DateUtils.DAY_IN_MILLIS) {
long count = millisUntilFinished / DateUtils.DAY_IN_MILLIS;
if(count > 1)
time.append(count).append(" Dias ");
else
time.append(count).append(" Dia ");
millisUntilFinished %= DateUtils.DAY_IN_MILLIS;
}
time.append(DateUtils.formatElapsedTime(Math.round(millisUntilFinished / 1000d)));
countDown.setText(time.toString());
}
@Override
public void onFinish() {
countDown.setText(DateUtils.formatElapsedTime(0));
countDown.setText("Dia del evento");
}
}.start();