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
36 { unit: 'year', seconds: 60 * 60 * 24 * 364 },
37 { unit: 'month', seconds: 60 * 60 * 24 * 30 },
38 { unit: 'day', seconds: 60 * 60 * 24 },
39 { unit: 'hour', seconds: 60 * 60 },
40 { unit: 'minute', seconds: 60 },
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 * 60 * 60) {
56 for (i = 0; i < timeUnits.length; i++) {
57 if (seconds >= timeUnits[i].seconds) {
58 var num = Math.floor(seconds / timeUnits[i].seconds);
59 seconds -= num * timeUnits[i].seconds;
62 ret += num + " " + timeUnits[i].unit + (num > 1 ? "s" : "") + " ";
72 ret = "less than a minute "
74 return ret + (offset < 0 ? "ago" : "from now");