End of the day countdown in javascript

Here’s how to have a realtime display showing how many hours, minutes, and seconds are left in the day:

Time left until midnight: <span id='HMSremaining'></span>
<script>
function calculateHMSleft()
{
	//calculate
	var now = new Date();
	var hoursleft = 23-now.getHours();
	var minutesleft = 59-now.getMinutes();
	var secondsleft = 59-now.getSeconds();

	//format 0 prefixes
	if(minutesleft<10) minutesleft = "0"+minutesleft;
	if(secondsleft<10) secondsleft = "0"+secondsleft;

	//display
	$('#HMSremaining').html(hoursleft+":"+minutesleft+":"+secondsleft);
}

calculateHMSleft();
setInterval(calculateHMSleft, 1000);
</script>

If you calculate how many days until an event, then you can append that and have a countdown timer to any holiday or special occasion!


Posted

in

,

by

Tags:

Comments

One response to “End of the day countdown in javascript”

  1. Uladzimir Avatar
    Uladzimir

    Thanks Shane, it works!
    Juts one little issue; right at the midnight when showing 00:00:00 it supposed to show 23:59:59 next second, but it shows 00:0-1:59 instead. How to fix that?

Leave a Reply to Uladzimir Cancel reply

Your email address will not be published. Required fields are marked *