倒数计时器到管理面板设置的日期

时间:2014-01-24 20:28:04

标签: javascript php timer admin countdown

我正在尝试制作一个倒计时器,它将倒计时到某个日期和时间。 我希望能够通过在文本框或类似内容中键入日期和时间(ex 2014-01-25, 15:00)从“管理面板”设置日期和时间。

正如您可能已经想到的那样,我不是PHP或JavaScript方面的佼佼者,而且我需要指导我的方法。

任何帮助都表示赞赏,因为我在过去2小时内没有取得任何进展。

2 个答案:

答案 0 :(得分:0)

要在没有像JQuery这样的框架的情况下执行此操作,您可以执行以下操作:

var MINUTE_IN_MILLISECONDS = 60 * 1000;
var HOUR_IN_MILLISECONDS = 60 * MINUTE_IN_MILLISECONDS;
var YEAR_IN_MILLISECONDS = 24 * HOUR_IN_MILLISECONDS;

var targetDate = new Date('2014-01-25 15:00');
var countdownInterval;

function countdown(){
    var currentDate = new Date();

    var difference = targetDate.getTime() - currentDate.getTime();

    //Countdown has expired, cancel interval and do other tasks here
    if(difference <= 0)
    {
        difference = 0;
        clearInterval(countdownInterval);

        //Update button here
    }


    var days = Math.floor(difference / YEAR_IN_MILLISECONDS);
    difference -= days * YEAR_IN_MILLISECONDS;

    var hours = Math.floor(difference / HOUR_IN_MILLISECONDS);
    difference -= hours * HOUR_IN_MILLISECONDS;

    var minutes = Math.floor(difference / MINUTE_IN_MILLISECONDS);
    difference -= minutes * MINUTE_IN_MILLISECONDS;

    var seconds = Math.floor(difference / 1000);

    console.log(days + ":" + hours + ":" + minutes + ":" + seconds);
}

countdownInterval = setInterval(countdown, 1000);

这是Fiddle

答案 1 :(得分:0)

完整演示: http://jsfiddle.net/DerekL/T48SL/

<form>
    <input type="date" required><input type="time" required>
    <input type="submit">
</form>
<span></span>
$("form").on("submit", function (e) {
    e.preventDefault();
    var date = $("input[type=date]").val(),
        time = $("input[type=time]").val(),
        targetTime = new Date(date + " " + time),
        interval = setInterval(function () {
            $("span").html(
                (((+startingTime - Date.now()) / 1000)|0) + " seconds left until " + startingTime.toString() + "."
            );
        }, 500);
});

使用代数格式化时间相当容易,而不仅仅是秒:

//yourTime is in seconds
(yourTime) % 60            //seconds
(yourTime / 60 |0) % 60    //minutes
(yourTime / 3600 |0) % 24  //hours
(yourTime / 86400 |0)      //days

/*
 *  Explanation:
 *   %  is mod, it finds the remainder of two numbers.
 *   |0 is binary OR, it rounds down a floating number.
 *
 */

使用这种技术,您不需要做一堆减法并在此过程中创建大量垃圾变量。