Question

I am trying to countdown to an event in android. the date and time for the event is stored in the database, but the Countdown returns more days than it should.

This is what have tried.

String EventDate="2013-12-26 15:00:00";

SimpleDateFormat FormatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm",Locale.US);
FormatDate.setTimeZone(TimeZone.getTimeZone("GMT+1"));

try {
    Date date = FormatDate.parse(mm);


    } catch (Exception e) {
    // TODO: handle exception
}
Long ToCount=date.getTime();
CountDownTimer cdt = new CountDownTimer(ToCount, 1000) {

    public void onTick(long millisUntilFinished) {
        EventTv.setText(""+ String.format(
        "%d Days,%d Hours, %d min, %d sec",
        TimeUnit.MILLISECONDS.toDays(millisUntilFinished),
        TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))

        ));


    }

    public void onFinish() {
        // TODO Auto-generated method stub
        EventTv.setText("done");

    }
}.start();

But if I run the app, the TextView shows (16059days,3875429hours,23125799min).

Please help me know what I am doing wrong?

Was it helpful?

Solution

The problem is with

date.getTime()

It is returning the number of milliseconds since Jan. 1, 1970, midnight GMT.

So to get the number of milliseconds from the current time you would need to use

Date now = new Date();
Long ToCount = date.getTime() - now.getTime();

Also to convert the millisUntilFinished to the relevant format you would want to use

TimeUnit.MILLISECONDS.toDays(millisUntilFinished),
TimeUnit.MILLISECONDS.toHours(millisUntilFinished) -
TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(millisUntilFinished)),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) -  
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - 
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top