Posted By

alp on 04/03/11


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

notturnale


Display dates as “time ago”


 / Published in: PHP
 

URL: http://www.phpsnippets.info/display-dates-as-time-ago

See http://codex.wordpress.org/FunctionReference/humantime_diff for Wordpress equivalent

  1. function timeAgo($timestamp, $granularity=2, $format='Y-m-d H:i:s'){
  2. $difference = time() - $timestamp;
  3. if($difference < 0) return '0 seconds ago';
  4. elseif($difference < 864000){
  5. $periods = array('week' => 604800,'day' => 86400,'hr' => 3600,'min' => 60,'sec' => 1);
  6. $output = '';
  7. foreach($periods as $key => $value){
  8. if($difference >= $value){
  9. $time = round($difference / $value);
  10. $difference %= $value;
  11. $output .= ($output ? ' ' : '').$time.' ';
  12. $output .= (($time > 1 && $key == 'day') ? $key.'s' : $key);
  13. $granularity--;
  14. }
  15. if($granularity == 0) break;
  16. }
  17. return ($output ? $output : '0 seconds').' ago';
  18. }
  19. else return date($format, $timestamp);
  20. }
  21.  
  22. Call:
  23.  
  24. $time = timeAgo($dateRef);

Report this snippet  

You need to login to post a comment.