Relative time extension


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /**
  2.  * Returns a description of this past date in relative terms.
  3.  * Takes an optional parameter (default: 0) setting the threshold in ms which
  4.  * is considered "Just now".
  5.  *
  6.  * Examples, where new Date().toString() == "Mon Nov 23 2009 17:36:51 GMT-0500 (EST)":
  7.  *
  8.  * new Date().toRelativeTime()
  9.  * --> 'Just now'
  10.  *
  11.  * new Date("Nov 21, 2009").toRelativeTime()
  12.  * --> '2 days ago'
  13.  *
  14.  * // One second ago
  15.  * new Date("Nov 23 2009 17:36:50 GMT-0500 (EST)").toRelativeTime()
  16.  * --> '1 second ago'
  17.  *
  18.  * // One second ago, now setting a now_threshold to 5 seconds
  19.  * new Date("Nov 23 2009 17:36:50 GMT-0500 (EST)").toRelativeTime(5000)
  20.  * --> 'Just now'
  21.  *
  22.  */
  23. Date.prototype.toRelativeTime = function(now_threshold) {
  24. var delta = new Date() - this;
  25.  
  26. now_threshold = parseInt(now_threshold, 10);
  27.  
  28. if (isNaN(now_threshold)) {
  29. now_threshold = 0;
  30. }
  31.  
  32. if (delta <= now_threshold) {
  33. return 'Just now';
  34. }
  35.  
  36. var units = null;
  37. var conversions = {
  38. millisecond: 1, // ms -> ms
  39. second: 1000, // ms -> sec
  40. minute: 60, // sec -> min
  41. hour: 60, // min -> hour
  42. day: 24, // hour -> day
  43. month: 30, // day -> month (roughly)
  44. year: 12 // month -> year
  45. };
  46.  
  47. for (var key in conversions) {
  48. if (delta < conversions[key]) {
  49. break;
  50. } else {
  51. units = key; // keeps track of the selected key over the iteration
  52. delta = delta / conversions[key];
  53. }
  54. }
  55.  
  56. // pluralize a unit when the difference is greater than 1.
  57. delta = Math.floor(delta);
  58. if (delta !== 1) { units += "s"; }
  59. return [delta, units, "ago"].join(" ");
  60. };
  61.  
  62. /*
  63.  * Wraps up a common pattern used with this plugin whereby you take a String
  64.  * representation of a Date, and want back a date object.
  65.  */
  66. Date.fromString = function(str) {
  67. return new Date(Date.parse(str));
  68. };

URL: http://github.com/jherdman/javascript-relative-time-helpers/blob/master/date.extensions.js

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.