1 // © 2006-2010 Joey Hess
2 // Redistribution and use in source and compiled forms, with or without
3 // modification, are permitted under any circumstances. No warranty.
5 // Causes html elements in the 'relativedate' class to be displayed
6 // as relative dates. The date is parsed from the title attribute, or from
7 // the element content.
11 hook("onload", getDates);
14 dateElements = getElementsByClass('relativedate');
15 for (var i = 0; i < dateElements.length; i++) {
16 var elt = dateElements[i];
17 var title = elt.attributes.title;
18 var d = new Date(title ? title.value : elt.innerHTML);
20 dateElements[i].date=d;
21 elt.title=elt.innerHTML;
28 function showDates() {
29 for (var i = 0; i < dateElements.length; i++) {
30 var elt = dateElements[i];
33 elt.innerHTML=relativeDate(d);
36 setTimeout(showDates,30000); // keep updating every 30s
40 { unit: 'year', seconds: 60 * 60 * 24 * 364 },
41 { unit: 'month', seconds: 60 * 60 * 24 * 30 },
42 { unit: 'day', seconds: 60 * 60 * 24 },
43 { unit: 'hour', seconds: 60 * 60 },
44 { unit: 'minute', seconds: 60 },
47 function relativeDate(date) {
49 var offset = date.getTime() - now.getTime();
50 var seconds = Math.round(Math.abs(offset) / 1000);
52 // hack to avoid reading just in the future if there is a minor
53 // amount of clock slip
54 if (offset >= 0 && seconds < 30 * 60 * 60) {
60 for (i = 0; i < timeUnits.length; i++) {
61 if (seconds >= timeUnits[i].seconds) {
62 var num = Math.floor(seconds / timeUnits[i].seconds);
63 seconds -= num * timeUnits[i].seconds;
66 ret += num + " " + timeUnits[i].unit + (num > 1 ? "s" : "") + " ";
76 ret = "less than a minute "
78 return ret + (offset < 0 ? "ago" : "from now");