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);
48 // hack to avoid reading just in the future if there is a minor
49 // amount of clock slip
50 if (offset >= 0 && seconds < 30 * timeUnits['minute']) {
56 for (i = 0; i < timeUnitOrder.length; i++) {
57 var unit = timeUnitOrder[i];
58 if (seconds >= timeUnits[unit]) {
59 var num = Math.floor(seconds / timeUnits[unit]);
60 seconds -= num * timeUnits[unit];
63 ret += num + " " + unit + (num > 1 ? "s" : "") + " ";
73 ret = "less than a minute "
75 return ret + (offset < 0 ? "ago" : "from now");