Simple function for converting unix timestamp to user friendly date


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

A simple function for converting a php timestamp (integer) to a user frindly format. Examples: 10 Seconds ago, 4 Days ago. The function converts timestamp to U.F. format only if the timestamp is earlyer than one week. Otherwise it uses $dateFormat argument to display the date.


Copy this code and paste it in your HTML
  1. <?php
  2. function user_friendly_date($timestamp, $echo = false, $dateFormat = 'm/d/Y H:i:s')
  3. {
  4. $ufdate = '';
  5. $now = time();
  6. $elapsed = $now - $timestamp;
  7. if($elapsed <= 0) $ufdate = 'Now';
  8. else if($elapsed == 1) $ufdate = "1 Second ago";
  9. else if($elapsed < 60) $ufdate = "{$elapsed} Seconds ago";
  10. else if($elapsed < 3600) //One hour in seconds
  11. {
  12. $mins = floor($elapsed/60);
  13. $secs = $elapsed%60;
  14. $disp = min(($secs <= 30 ? $mins : $mins + 1), 59);
  15. $ufdate = "{$disp} Minute" . ($disp == 1 ? '' : 's') ." ago";
  16. }
  17. else if($elapsed < 86400) //One day in seconds
  18. {
  19. $hours = floor($elapsed/3600);
  20. $mins = floor(($elapsed%3600)/60);
  21. $disp = min(($mins <= 30 ? $hours : $hours + 1), 23);
  22. $ufdate = "{$disp} Hour" . ($disp == 1 ? '' : 's') ." ago";
  23. }
  24. else if($elapsed < 604800) //One week in seconds
  25. {
  26. $days = floor($elapsed/86400);
  27. $hours = floor(($elapsed%86400)/3600);
  28. $disp = min(($hours <= 12 ? $days : $days + 1), 6);
  29. $ufdate = "{$disp} Day" . ($disp == 1 ? '' : 's') ." ago";
  30. }
  31. else $ufdate = date($dateFormat, $timestamp);
  32. if($echo) echo $ufdate;
  33. return $ufdate;
  34. }
  35.  
  36. //Usage
  37. $now = time();
  38. $tenSecsAgo = $now - 10;
  39. $oneMinuteAgo = $now - 60;
  40. $thirtyNineMinsAgo = $now - (39 * 60); //minutes * seconds
  41. $elevenHoursAgo = $now - (11 * 60 * 60); //hours * minutes * seconds
  42. $twoDaysAgo = $now - (2 * 24 * 60 * 60); //days * hours * minutes * seconds
  43.  
  44. echo "<p>\n";
  45. echo user_friendly_date($tenSecsAgo), " <br>\n";
  46. echo user_friendly_date($oneMinuteAgo), " <br>\n";
  47. echo user_friendly_date($thirtyNineMinsAgo), " <br>\n";
  48. echo user_friendly_date($elevenHoursAgo), " <br>\n";
  49. echo user_friendly_date($twoDaysAgo), " <br>\n";
  50. echo "</p>";
  51. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.