开发者

Display real time years, months, weeks and days between 2 days in JavaScript

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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜