To Relative Time


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

* Returns a description of this past date in relative terms.
* Takes an optional parameter (default: 0) setting the threshold in ms which
* is considered "Just now".
*
* Examples, where new Date().toString() == "Mon Nov 23 2009 17:36:51 GMT-0500 (EST)":
*
* new Date().toRelativeTime()
* --> 'Just now'
*
* new Date("Nov 21, 2009").toRelativeTime()
* --> '2 days ago'
*
* // One second ago
* new Date("Nov 23 2009 17:36:50 GMT-0500 (EST)").toRelativeTime()
* --> '1 second ago'
*
* // One second ago, now setting a now_threshold to 5 seconds
* new Date("Nov 23 2009 17:36:50 GMT-0500 (EST)").toRelativeTime(5000)
* --> 'Just now'
*
*/


Copy this code and paste it in your HTML
  1. Date.prototype.toRelativeTime = function(now_threshold) {
  2. var delta = new Date() - this;
  3.  
  4. now_threshold = parseInt(now_threshold, 10);
  5.  
  6. if (isNaN(now_threshold)) {
  7. now_threshold = 0;
  8. }
  9.  
  10. if (delta <= now_threshold) {
  11. return 'Just now';
  12. }
  13.  
  14. var units = null;
  15. var conversions = {
  16. millisecond: 1, // ms -> ms
  17. second: 1000, // ms -> sec
  18. minute: 60, // sec -> min
  19. hour: 60, // min -> hour
  20. day: 24, // hour -> day
  21. month: 30, // day -> month (roughly)
  22. year: 12 // month -> year
  23. };
  24.  
  25. for (var key in conversions) {
  26. if (delta < conversions[key]) {
  27. break;
  28. } else {
  29. units = key; // keeps track of the selected key over the iteration
  30. delta = delta / conversions[key];
  31. }
  32. }
  33.  
  34. // pluralize a unit when the difference is greater than 1.
  35. delta = Math.floor(delta);
  36. if (delta !== 1) { units += "s"; }
  37. return [delta, units].join(" ");
  38. };

URL: https://raw.github.com/ry/node_chat/master/client.js

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.