Javascript parse relative date


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

This takes a very readable date, such as "Fri, 4 Dec 2008 15:13:00 +0000", and outputs it as a relative date (such as "1 hour ago").


Copy this code and paste it in your HTML
  1. var d = Date.parse("Fri, 4 Dec 2008 15:13:00 +0000");
  2. var dateFunc = new Date();
  3. var timeSince = dateFunc.getTime() - d;
  4. var inSeconds = timeSince / 1000;
  5. var inMinutes = timeSince / 1000 / 60;
  6. var inHours = timeSince / 1000 / 60 / 60;
  7. var inDays = timeSince / 1000 / 60 / 60 / 24;
  8. var inYears = timeSince / 1000 / 60 / 60 / 24 / 365;
  9.  
  10. // in seconds
  11. if(Math.round(inSeconds) == 1){
  12. document.write("1 second ago");
  13. }
  14. else if(inMinutes < 1.01){
  15. document.write(Math.round(inSeconds) + " seconds ago");
  16. }
  17.  
  18. // in minutes
  19. else if(Math.round(inMinutes) == 1){
  20. document.write("1 minute ago");
  21. }
  22. else if(inHours < 1.01){
  23. document.write(Math.round(inMinutes) + " minutes ago");
  24. }
  25.  
  26. // in hours
  27. else if(Math.round(inHours) == 1){
  28. document.write("1 hour ago");
  29. }
  30. else if(inDays < 1.01){
  31. document.write(Math.round(inHours) + " hours ago");
  32. }
  33.  
  34. // in days
  35. else if(Math.round(inDays) == 1){
  36. document.write("1 day ago");
  37. }
  38. else if(inYears < 1.01){
  39. document.write(Math.round(inDays) + " days ago");
  40. }
  41.  
  42. // in years
  43. else if(Math.round(inYears) == 1){
  44. document.write("1 year ago");
  45. }
  46. else
  47. {
  48. document.write(Math.round(inYears) + " years ago");
  49. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.