]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - underlays/javascript/relativedate.js
fix link to Jason Blevins user page
[git.ikiwiki.info.git] / underlays / javascript / relativedate.js
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.
5 var dateElements;
7 hook("onload", getDates);
9 function 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);
15                 if (! isNaN(d)) {
16                         dateElements[i].date=d;
17                         elt.title=elt.innerHTML;
18                 }
19         }
21         showDates();
22 }
24 function showDates() {
25         for (var i = 0; i < dateElements.length; i++) {
26                 var elt = dateElements[i];
27                 var d = elt.date;
28                 if (! isNaN(d)) {
29                         elt.innerHTML=relativeDate(d);
30                 }
31         }
32         setTimeout(showDates,30000); // keep updating every 30s
33 }
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) {
44         var now = new Date();
45         var offset = date.getTime() - now.getTime();
46         var seconds = Math.round(Math.abs(offset) / 1000);
48         var ret = "";
49         var shown = 0;
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];
55                         if (ret)
56                                 ret += "and ";
57                         ret += num + " " + unit + (num > 1 ? "s" : "") + " ";
59                         if (++shown == 2)
60                                 break;
61                 }
62                 else if (shown)
63                         break;
64         }
66         if (! ret)
67                 ret = "less than a minute "
69         return ret + (offset < 0 ? "ago" : "from now");
70 }