CountDownTimer无法正确显示时间

时间:2013-08-04 17:36:58

标签: java android date calendar countdown

我正在为Android开发。我正在使用倒计时器来显示特定日期的倒计时。在这篇文章发表时,它应该显示接近18dys 12hrs 30min 55s的内容。但我得到了49dys 19hrs 28min 31s。我相信我转换为可读日期是正确的,但话说回来,我没有使用此计时器的经验。我的研究让我圈起来了。请查看我的代码,发现我可能遇到的任何错误。提前致谢。

private void startCountdown() {
    CountDownTimer mCountDownTimer;
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal2.set(Calendar.YEAR, 2013);
        cal2.set(Calendar.MONTH, 8);
        cal2.set(Calendar.DAY_OF_MONTH, 23);
        cal2.set(Calendar.HOUR_OF_DAY, 7);
        cal2.set(Calendar.MINUTE, 0);

    long diffInMillis = cal2.getTimeInMillis() - cal1.getTimeInMillis();



        tvCount = (TextView) findViewById(R.id.tvCountdown);

        mCountDownTimer = new CountDownTimer(diffInMillis, 1000) {


            @Override
            public void onFinish() {
                tvCount.setText("VIEW FIGHT CARD");

            }

            @Override
            public void onTick(long millisUntilFinished) {

                String  days = null, hours = null, minutes = null, seconds = null;
                long count = millisUntilFinished / DateUtils.DAY_IN_MILLIS;
                if(millisUntilFinished > DateUtils.DAY_IN_MILLIS) {

                    if(count > 1)
                        days = (count)+("dys ");
                    else
                        days = (count)+("dy ");

                    millisUntilFinished %= DateUtils.DAY_IN_MILLIS;
                }
                if(millisUntilFinished > DateUtils.HOUR_IN_MILLIS) {
                    count = millisUntilFinished / DateUtils.HOUR_IN_MILLIS;
                    if(count > 1)
                       hours = (count) + "hrs ";
                    else
                        hours = count + "hr ";

                    millisUntilFinished %= DateUtils.HOUR_IN_MILLIS;
                }
                if(millisUntilFinished > DateUtils.MINUTE_IN_MILLIS) {
                    count = millisUntilFinished / DateUtils.MINUTE_IN_MILLIS;

                    minutes = count + "min";

                    millisUntilFinished %= DateUtils.MINUTE_IN_MILLIS;
                }
                if(millisUntilFinished > DateUtils.SECOND_IN_MILLIS) {
                    count = millisUntilFinished / DateUtils.SECOND_IN_MILLIS;

                    seconds = count + "s";

                    millisUntilFinished %= DateUtils.SECOND_IN_MILLIS;
                }



                tvCount.setText(days + hours + minutes +seconds + "");
            }
        };
    mCountDownTimer.start();
    }

1 个答案:

答案 0 :(得分:1)

不要忘记在Java中月份是0索引所以

1月= 0,2月= 1,...,8月= 7

使用更安全

cal2.set(Calendar.MONTH, Calendar.AUGUST);