1 // Causes html elements in the 'relativedate' class to be displayed
2 // as relative dates. The date is parsed from the title attribute, or from
3 // the element content.
7 hook("onload", getDates);
10 dateElements = getElementsByClass('relativedate');
11 for (var i = 0; i < dateElements.length; i++) {
12 var elt = dateElements[i];
13 var title = elt.attributes.title;
14 var d = new Date(title ? title.value : elt.innerHTML);
16 dateElements[i].date=d;
17 elt.title=elt.innerHTML;
24 function showDates() {
25 for (var i = 0; i < dateElements.length; i++) {
26 var elt = dateElements[i];
29 elt.innerHTML=relativeDate(d);
32 setTimeout(showDates,30000); // keep updating every 30s
35 var timeUnits = new Array;
36 timeUnits['minute'] = 60;
37 timeUnits['hour'] = timeUnits['minute'] * 60;
38 timeUnits['day'] = timeUnits['hour'] * 24;
39 timeUnits['month'] = timeUnits['day'] * 30;
40 timeUnits['year'] = timeUnits['day'] * 364;
41 var timeUnitOrder = ['year', 'month', 'day', 'hour', 'minute'];
43 function relativeDate(date) {
45 var offset = date.getTime() - now.getTime();
46 var seconds = Math.round(Math.abs(offset) / 1000);
50 for (i = 0; i < timeUnitOrder.length; i++) {
51 var unit = timeUnitOrder[i];
52 if (seconds >= timeUnits[unit]) {
53 var num = Math.floor(seconds / timeUnits[unit]);
54 seconds -= num * timeUnits[unit];
57 ret += num + " " + unit + (num > 1 ? "s" : "") + " ";
67 ret = "less than a minute "
69 return ret + (offset < 0 ? "ago" : "from now");