summaryrefslogtreecommitdiff
path: root/underlays/javascript/ikiwiki/relativedate.js
blob: 2a270d627abd45c706d9de78224f681dc96fd7d1 (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 = [
  30. { unit: 'year', seconds: 60 * 60 * 24 * 364 },
  31. { unit: 'month', seconds: 60 * 60 * 24 * 30 },
  32. { unit: 'day', seconds: 60 * 60 * 24 },
  33. { unit: 'hour', seconds: 60 * 60 },
  34. { unit: 'minute', seconds: 60 },
  35. ];
  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 * 60 * 60) {
  43. return "just now";
  44. }
  45. var ret = "";
  46. var shown = 0;
  47. for (i = 0; i < timeUnits.length; i++) {
  48. if (seconds >= timeUnits[i].seconds) {
  49. var num = Math.floor(seconds / timeUnits[i].seconds);
  50. seconds -= num * timeUnits[i].seconds;
  51. if (ret)
  52. ret += "and ";
  53. ret += num + " " + timeUnits[i].unit + (num > 1 ? "s" : "") + " ";
  54. if (++shown == 2)
  55. break;
  56. }
  57. else if (shown)
  58. break;
  59. }
  60. if (! ret)
  61. ret = "less than a minute "
  62. return ret + (offset < 0 ? "ago" : "from now");
  63. }