Search code examples
javascriptphpmysqldatecountdown

Countdown from Database (date)


So what I would like to do is make a countdown based on the date from mysql and make it going down in live mode without the need to refresh.

Code:

<?php 
    $date = strtotime($row_tournaments['date']);
    $remaining = $date - time();
    $days_remaining = floor($remaining / 86400);
    $hours_remaining = floor(($remaining % 86400) / 3600);
    $minutes_remaining = floor(($remaining % 3600) / 60);
    $seconds_remaining = ($remaining % 60);
    echo "<p>$days_remaining <span style='font-size:.3em;'>dias</span> $hours_remaining <span style='font-size:.3em;'>horas</span> $minutes_remaining <span style='font-size:.3em;'>minutos</span> $seconds_remaining <span style='font-size:.3em;'>segundos</span></p>";
?>

This works fine but I need to refresh so I can see the time going down.

$date = strtotime($row_tournaments['date']);

This is geting the date from database which the format is:

2015-10-11 08:15:31

Solution

  • var initialTime = 194801;//Place here the total of seconds you receive on your PHP code. ie: var initialTime = <? echo $remaining; ?>;
    
    var seconds = initialTime;
    function timer() {
        var days        = Math.floor(seconds/24/60/60);
        var hoursLeft   = Math.floor((seconds) - (days*86400));
        var hours       = Math.floor(hoursLeft/3600);
        var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
        var minutes     = Math.floor(minutesLeft/60);
        var remainingSeconds = seconds % 60;
        if (remainingSeconds < 10) {
            remainingSeconds = "0" + remainingSeconds; 
        }
        document.getElementById('countdown').innerHTML = days + "dias " + hours + "horas " + minutes + "minutos " + remainingSeconds+ "segundos";
        if (seconds == 0) {
            clearInterval(countdownTimer);
            document.getElementById('countdown').innerHTML = "Completed";
        } else {
            seconds--;
        }
    }
    var countdownTimer = setInterval('timer()', 1000);
    <span id="countdown" class="timer"></span>