Posted By

wbowers on 03/09/08


Tagged

javascript js time function conversion convert seconds elapsed


Versions (?)

Elapsed time string from time in seconds


 / Published in: JavaScript
 

URL: http://jonaquino.blogspot.com/2006/12/twitter-increasing-number-of-twitters.html

  1. function elapsedTime (createdAt)
  2. {
  3. var ageInSeconds = (new Date().getTime() - new Date(createdAt).getTime()) / 1000;
  4. var s = function(n) { return n == 1 ? '' : 's' };
  5. if (ageInSeconds < 0) {
  6. return 'just now';
  7. }
  8. if (ageInSeconds < 60) {
  9. var n = ageInSeconds;
  10. return n + ' second' + s(n) + ' ago';
  11. }
  12. if (ageInSeconds < 60 * 60) {
  13. var n = Math.floor(ageInSeconds/60);
  14. return n + ' minute' + s(n) + ' ago';
  15. }
  16. if (ageInSeconds < 60 * 60 * 24) {
  17. var n = Math.floor(ageInSeconds/60/60);
  18. return n + ' hour' + s(n) + ' ago';
  19. }
  20. if (ageInSeconds < 60 * 60 * 24 * 7) {
  21. var n = Math.floor(ageInSeconds/60/60/24);
  22. return n + ' day' + s(n) + ' ago';
  23. }
  24. if (ageInSeconds < 60 * 60 * 24 * 31) {
  25. var n = Math.floor(ageInSeconds/60/60/24/7);
  26. return n + ' week' + s(n) + ' ago';
  27. }
  28. if (ageInSeconds < 60 * 60 * 24 * 365) {
  29. var n = Math.floor(ageInSeconds/60/60/24/31);
  30. return n + ' month' + s(n) + ' ago';
  31. }
  32. var n = Math.floor(ageInSeconds/60/60/24/365);
  33. return n + ' year' + s(n) + ' ago';
  34. }
  35.  
  36. // Make date parseable in IE
  37. function fixDate (d)
  38. {
  39. var a = d.split(' ');
  40. var year = a.pop();
  41. return a.slice(0, 3).concat([year]).concat(a.slice(3)).join(' ');
  42. }

Report this snippet  

You need to login to post a comment.