Relative Time Function


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



Copy this code and paste it in your HTML
  1. <?php
  2. function relativeTime($time = false, $limit = 86400, $format = 'g:i A M jS') {
  3. if (empty($time) || (!is_string($time) &amp;&amp; !is_numeric($time))) $time = time();
  4. elseif (is_string($time)) $time = strtotime($time);
  5.  
  6. $now = time();
  7. $relative = '';
  8.  
  9. if ($time === $now) $relative = 'now';
  10. elseif ($time > $now) $relative = 'in the future';
  11. else {
  12. $diff = $now - $time;
  13.  
  14. if ($diff >= $limit) $relative = date($format, $time);
  15. elseif ($diff < 60) {
  16. $relative = 'less than one minute ago';
  17. } elseif (($minutes = ceil($diff/60)) < 60) {
  18. $relative = $minutes.' minute'.(((int)$minutes === 1) ? '' : 's').' ago';
  19. } else {
  20. $hours = ceil($diff/3600);
  21. $relative = 'about '.$hours.' hour'.(((int)$hours === 1) ? '' : 's').' ago';
  22. }
  23. }
  24.  
  25. return $relative;
  26. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.