summaryrefslogtreecommitdiff
path: root/underlays/javascript/relativedate.js
blob: 5142332f1132b833fe119764a5c0055519551790 (plain)
  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.
  4. var dateElements;
  5. hook("onload", getDates);
  6. function getDates() {
  7. dateElements = getElementsByClass('relativedate');
  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. // hack to avoid reading just in the future if there is a minor
  41. // amount of clock slip
  42. if (offset >= 0 && seconds < 30 * timeUnits['minute']) {
  43. return "just now";
  44. }
  45. var ret = "";
  46. var shown = 0;
  47. for (i = 0; i < timeUnitOrder.length; i++) {
  48. var unit = timeUnitOrder[i];
  49. if (seconds >= timeUnits[unit]) {
  50. var num = Math.floor(seconds / timeUnits[unit]);
  51. seconds -= num * timeUnits[unit];
  52. if (ret)
  53. ret += "and ";
  54. ret += num + " " + unit + (num > 1 ? "s" : "") + " ";
  55. if (++shown == 2)
  56. break;
  57. }
  58. else if (shown)
  59. break;
  60. }
  61. if (! ret)
  62. ret = "less than a minute "
  63. return ret + (offset < 0 ? "ago" : "from now");
  64. }