Relative Date Parse


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



Copy this code and paste it in your HTML
  1. function normalizeDate(time)
  2. {
  3. var values = time.split(" ");
  4. time = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  5. var parsed_date = Date.parse(time);
  6. var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  7. var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  8. delta = delta + (relative_to.getTimezoneOffset() * 60);
  9.  
  10. var out = '';
  11. if (delta < 60)
  12. {
  13. out = 'a minute ago';
  14. } else if(delta < 120)
  15. {
  16. out = 'couple of minutes ago';
  17. } else if(delta < (45*60))
  18. {
  19. out = (parseInt(delta / 60)).toString() + ' minutes ago';
  20. } else if(delta < (90*60))
  21. {
  22. out = 'an hour ago';
  23. } else if(delta < (24*60*60))
  24. {
  25. out = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
  26. } else if(delta < (48*60*60))
  27. {
  28. out = '1 day ago';
  29. } else
  30. {
  31. out = (parseInt(delta / 86400)).toString() + ' days ago';
  32. }
  33.  
  34. return out;
  35. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.