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


this i've coded up, , appears 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 = new date();           var difference = - 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 , ' + days + ' days';     }, 500);  }; 

this seems update span fine, , numbers look correct.

however, code looks quite ugly. need set faux constants that, , math calculate want?

it's been while since i've worked date object.

is best way this?

you put constants in array , 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 = [];   (var = 0; < units.length; ++i) {     rv.push(math.floor(diff / units[i]));     diff = diff % units[i];   }   return rv; } 

of course since months , years aren't same length, isn't accurate, figure realize :-)

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


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -