This is what I've coded it up, and it appears to work.
window.onload = function() {
var currentSpan = document.getElementById('current');
var minute = 60000,
hour = minute * 60,
day = hour * 24,
week = day * 7,
month = week * 4,
year = day * 365;
var start = new Date(2009, 6, 1);
setInterval(function() {
var now = new Date();
var difference = now - start;
var years = Math.floor(difference / year),
months = Math.floor((difference - (years * year)) / month),
weeks = Math.floor((difference - (months * month + years * year)) / week),
days = Math.floor((difference - (weeks * week + months * month + years * year)) / day);
currentSpan.innerHTML = 'Since has passed: ' + years + ' years, ' + months + ' months, ' + weeks + ' weeks and ' + days + ' days';
}, 500);
};
This seems to update my span fine, and all the numbers look correct.
However, the code looks quite ugly. Do I really need to set up faux constants like that, and then do all that math to calculate what I want?
It's been a while since I've worked with the Date
object.
Is this the best way to do this?