JavaScript Date Difference Counter


A simple JavaScript function that outputs the approximate date difference in years, days, hours, minutes and seconds between the supplied date and now. (It does not account for leap years) For this example the supplied date is hardcoded as June 13, 2009 1:00:00PM.

function DateDiff(datestr) {
var seconds = Math.floor((new Date().getTime()-Date.parse(datestr))/1000);
var minutes = Math.floor(seconds/60);
var hours = Math.floor(minutes/60);
var days = Math.floor(hours/24);
var years = Math.floor(days/365);
seconds = seconds - minutes * 60;
minutes = minutes - hours * 60;
hours = hours - days * 24;
days = days - years * 365;
return years + "yrs " + days + "days " + hours + "hrs " + minutes + "min " + seconds + "sec";
}
function updateCounter() {
document.getElementById('Counter').innerHTML = DateDiff('2009-06-13 13:00:00');
}
var t = setInterval(updateCounter, 1000);

 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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