Display dates as “time ago”


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

See http://codex.wordpress.org/Function_Reference/human_time_diff for Wordpress equivalent


Copy this code and paste it in your HTML
  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);

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.