Calculate remaining time in days, hours, minutes and seconds – Javascript, PHP

Demo

Convert time to different timezones

Today, we will learn to calculate remaining time till future date in days, hours, minutes and seconds. Either you are receiving values in PHP variable from MySQL database, or you are calling an AJAX request, this tutorial will help you in both situations. We will also display the hours, minutes and seconds in leading zeroes.

So you will not see time as “7:9:3” but you will see that as “07:09:03” using leading zeroes. We already uploaded 1 more tutorial on creating a countdown timer using libraries. If you are comfortable to use third party libraries in your project, you can follow our tutorial on that as well.

Using third party library

Basically, we are going to get the difference between current date and the date in future. Then we will extract the days, hours, minutes and hours from that difference. Difference will be in seconds so we have to apply some math on it. First we assume that you are already receiving the value from your MySQL database in PHP variable. We have set the PHP variable below but you can use your own database value:

<?php
	$date = "2020-06-07 23:39:00";
?>

Then we will create a <div> where we will display the remaining time and a hidden input field to get the PHP variable value in Javascript.

<div id="data"></div>

<input type="hidden" id="date" value="<?php echo $date; ?>">

JS function when page loads

Then create a Javascript function which will be called once simply when the page loads. And then in a setInterval function which will be called each second, so we will display the remaining time in seconds as well. We will get 2 date objects, first will be current date and second will be date in future which we are getting from PHP variable.

Then we will get the timestamp from both dates in milliseconds using getTime() function. Dividing that by 1000 will convert that in seconds. But we will also get the floating numbers when dividing, we can prevent the floating number by calling toFixed(0) function.

Convert string to double – Javascript

Since toFixed() function returns a string which will not be helpful in getting the difference between 2 dates, so we have to convert that in double or float. We can do that by calling Math.abs() function, it will return the absolute value. Then we subtract the current timestamp from future timestamp and save that in a variable diff as difference.

This diff variable is also in seconds, now we have to convert that value into days, hours, minutes and seconds. We know that there are 86400 seconds in each day, so dividing the difference by 86400 will return the number of days remaining. And since dividing also cause floating number, so we can prevent that by calling Math.floor() function. It will round the value to the previous number.

For example, if the value is 23.7 then it will return as 23. Time to get the remaining hours, we know that there are 3600 seconds in each hour, so we will divide that difference by 3600, round the value to floor. And since there are 24 hours in each day, so we have to take the modulus by 24. Taking modulus will divide the value and return the remainder.

Get seconds from timestamp – Javascript

To get the minutes, we know that there are 60 seconds in each minute and 60 minutes in each hour. So we divide the difference by 60, round the value by floor, then take the modulus by 60. That will return the number of minutes remaining till date. To get the seconds, is the simplest among all.

We know the limit for seconds is 60, so we simply take the modulus of difference by 60 and it will return the seconds. If you want to show the leading zeros i.e. zeroes on left if value is less than 10, then you can also put a condition on days, hours, minutes and seconds. Check if the value is less than 10, then prepend the “0” with value. And finally display that in our <div id=”data”></div>

Make sure to call the function in setInterval to update the value each second. Following function will calculate the remaining time.

<script>
    function func() {
        var dateValue = document.getElementById("date").value;

        var date = Math.abs((new Date().getTime() / 1000).toFixed(0));
        var date2 = Math.abs((new Date(dateValue).getTime() / 1000).toFixed(0));

        var diff = date2 - date;

        var days = Math.floor(diff / 86400);
        var hours = Math.floor(diff / 3600) % 24;
        var minutes = Math.floor(diff / 60) % 60;
        var seconds = diff % 60;

        var daysStr = days;
        if (days < 10) {
            daysStr = "0" + days;
        }
 
        var hoursStr = hours;
        if (hours < 10) {
            hoursStr = "0" + hours;
        }
 
        var minutesStr = minutes;
        if (minutes < 10) {
            minutesStr = "0" + minutes;
        }
 
        var secondsStr = seconds;
        if (seconds < 10) {
            secondsStr = "0" + seconds;
        }

        if (days < 0 && hours < 0 && minutes < 0 && seconds < 0) {
            daysStr = "00";
            hoursStr = "00";
            minutesStr = "00";
            secondsStr = "00";

            console.log("close");
            if (typeof interval !== "undefined") {
                clearInterval(interval);
            }
        }

        document.getElementById("data").innerHTML = daysStr + " days, " + hoursStr + ":" + minutesStr + ":" + secondsStr;
    }

    func();
    var interval = setInterval(func, 1000);
</script>

That’s how you can calculate the remaining time till date in Javascript.

[wpdm_package id=’421′]