Question

I am trying to make a countdown timer that will countdown to a certain date and time. I would like to be able to set the date and time from a 'admin panel' by typing in the date and time(ex 2014-01-25, 15:00) in a textbox or something similar.

As you might've figured, I'm not the best at PHP or JavaScript and I'm in need of directions as of how I would do this.

Any help is appreciated as I haven't made any progress in the last 2 hours I've tried doing this.

Was it helpful?

Solution

To do this with no frameworks like JQuery, you can do the following:

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);

Here's the Fiddle

OTHER TIPS

Full demonstration: 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);
});

It is fairly easy to format the time instead of just seconds with Algebra:

//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.
 *
 */

With this technique, you do not need to do a bunch of subtraction and create a lot of junk variables in the process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top