views:

46

answers:

2

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?

A: 

You don't have to set up any constants, but if you need all those numbers (years, months, days, hours etc) I don't know of any other way it can be done.

edl
+1  A: 

You could put those constants in an array and then just iterate through it:

function tdiff(utc) {
  var diff = new Date() - new Date(utc);
  var units = [
    1000 * 60 * 60 * 24 * 365,
    1000 * 60 * 60 * 24 * 28,
    1000 * 60 * 60 * 24 * 7,
    1000 * 60 * 60 * 24,
    1000 * 60 * 60,
    1000 * 60,
    1000
  ];

  var rv = [];
  for (var i = 0; i < units.length; ++i) {
    rv.push(Math.floor(diff / units[i]));
    diff = diff % units[i];
  }
  return rv;
}

Of course since months and years aren't always the same length, this isn't really that accurate, but I figure you realize that :-)

Also see this: http://timeago.yarp.com/ it's kind-of cool

Pointy
Ah yep, I took into consideration it is not 100% accurate. Also, looks like a cool plugin, but I'm including this in a project without jQuery. Thanks for your answer +1
alex