倒计时时钟的问题

时间:2011-04-19 20:39:15

标签: php javascript date time

基本上我现在有时间显示时间,但倒计时不起作用。我最初从here获取了代码,并对其进行了调整。

我要做的是让倒计时从我从数据库中检索到的持续时间倒计时。

这是我如何检索我的持续时间:

//TRANSFORM MYSQL TIME INTO SECONDS

    $duration_array = explode(':', $duration);

    $length = ((int)$duration_array[0] * 3600) + ((int)$duration_array[1] * 60) + (int)$duration_array[2];

    //CALCULATE FINISH TIME WITH START TIME AND DURATION.
    $target_time = $length + time();

我正在将此解析成我的JavaScript倒计时函数并转换为javascript date()对象。

但目前时钟不倒计时。

这是我的javascript:

function countdown_clock(target_time)
         {
         html_code = '<div id="countdown"></div>';

         document.write(html_code);

     var timetarget = new Date(target_time *1000);

         countdown(timetarget);

         }


function countdown(timetarget)
         {

     var Today = new Date();

     Todays_Year = Today.getFullYear() - 2000;
         Todays_Month = Today.getMonth();

         //Convert both today's date and the target date into miliseconds.
         Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(),Today.getHours(),Today.getMinutes(),Today.getSeconds())).getTime();

     Target_Date = timetarget.getTime();

         //Find their difference, and convert that into seconds.
         Time_Left = Math.round((Target_Date - Todays_Date) / 1000);

         if(Time_Left < 0)
            Time_Left = 0;

        var innerHTML = '';

         //More datailed.
        days = Math.floor(Time_Left / (60 * 60 * 24));
        Time_Left %= (60 * 60 * 24);
        hours = Math.floor(Time_Left / (60 * 60));
        Time_Left %= (60 * 60);
        minutes = Math.floor(Time_Left / 60);
        Time_Left %= 60;
        seconds = Time_Left;

    if (seconds < 10){seconds = '0' + seconds;}
    if (minutes < 10){minutes = '0' + minutes;}

        innerHTML = hours + ':' + minutes + ':' + seconds + ' secs' ;

        document.getElementById('countdown').innerHTML = innerHTML;

         //Recursive call, keeps the clock ticking.
        setTimeout('countdown('+timetarget+');', 1000);
        }

我似乎真的在与整个约会对象挣扎,所以任何帮助都会很棒。

感谢,

1 个答案:

答案 0 :(得分:1)

我认为问题是您的timetarget变量正在失去它是Date对象的事实。我修复它made a jsFiddle,它似乎正在工作(倒计时)。

编辑:此外,我认为Javascript可能因为您使用innerHTML作为变量名而搞砸了,这是我做的另一项更改。

编辑2 :这是一些slightly cleaned up code的更新。