Date Time Countdown Tutorial Christmas 2012 Doomsday
Learn to build JavaScript countdown applications for any target date and time. We use the JavaScript date object to establish two dates to work between with our simple calculations. Once we get the total seconds between the two dates and times we can break the seconds down to minutes, hours, days and even years if your target date is far into the future.
<!DOCTYPE html>
<html>
<head>
<script>
function cdtd() {
var xmas = new Date("December 25, 2012 00:01:00");
var now = new Date();
var timeDiff = xmas.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
document.write("Christmas is here!");
// Run any code needed for countdown completion here
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('cdtd()',1000);
}
</script>
</head>
<body>
Days Remaining:
<div id="daysBox"></div>
Hours Remaining:
<div id="hoursBox"></div>
Minutes Remaining:
<div id="minsBox"></div>
Seconds Remaining:
<div id="secsBox"></div>
<script>cdtd();</script>
</body>
</html>