summaryrefslogtreecommitdiff
path: root/underlays/javascript/relativedate.js
blob: c5e62b3cc13a95bdfb4eed0cade062619a2b8a24 (plain)
  1. // Causes html elements in the 'date' and 'pagedate' classes to be displayed
  2. // as relative dates. The date is parsed from the title attribute, or from
  3. // the element content.
  4. var dateElements;
  5. hook("onload", getDates);
  6. function getDates() {
  7. dateElements = getElementsByClass('date');
  8. for (var i = 0; i < dateElements.length; i++) {
  9. var elt = dateElements[i];
  10. var title = elt.attributes.title;
  11. var d = new Date(title ? title.value : elt.innerHTML);
  12. if (! isNaN(d)) {
  13. dateElements[i].date=d;
  14. elt.title=elt.innerHTML;
  15. }
  16. }
  17. showDates();
  18. }
  19. function showDates() {
  20. for (var i = 0; i < dateElements.length; i++) {
  21. var elt = dateElements[i];
  22. var d = elt.date;
  23. if (! isNaN(d)) {
  24. elt.innerHTML=relativeDate(d);
  25. }
  26. }
  27. setTimeout(showDates,30000); // keep updating every 30s
  28. }
  29. var timeUnits = new Array;
  30. timeUnits['minute'] = 60;
  31. timeUnits['hour'] = timeUnits['minute'] * 60;
  32. timeUnits['day'] = timeUnits['hour'] * 24;
  33. timeUnits['month'] = timeUnits['day'] * 30;
  34. timeUnits['year'] = timeUnits['day'] * 364;
  35. var timeUnitOrder = ['year', 'month', 'day', 'hour', 'minute'];
  36. function relativeDate(date) {
  37. var now = new Date();
  38. var offset = date.getTime() - now.getTime();
  39. var seconds = Math.round(Math.abs(offset) / 1000);
  40. var ret = "";
  41. var shown = 0;
  42. for (i = 0; i < timeUnitOrder.length; i++) {
  43. var unit = timeUnitOrder[i];
  44. if (seconds >= timeUnits[unit]) {
  45. var num = Math.floor(seconds / timeUnits[unit]);
  46. seconds -= num * timeUnits[unit];
  47. if (ret)
  48. ret += "and ";
  49. ret += num + " " + unit + (num > 1 ? "s" : "") + " ";
  50. if (++shown == 2)
  51. break;
  52. }
  53. else if (shown)
  54. break;
  55. }
  56. if (! ret)
  57. ret = "less than a minute "
  58. return ret + (offset < 0 ? "ago" : "from now");
  59. }