Return to Snippet

Revision: 43930
at April 3, 2011 17:43 by alp


Initial Code
function  timeAgo($timestamp, $granularity=2, $format='Y-m-d H:i:s'){
        $difference = time() - $timestamp;
        if($difference < 0) return '0 seconds ago';
        elseif($difference < 864000){
                $periods = array('week' => 604800,'day' => 86400,'hr' => 3600,'min' => 60,'sec' => 1);
                $output = '';
                foreach($periods as $key => $value){
                        if($difference >= $value){
                                $time = round($difference / $value);
                                $difference %= $value;
                                $output .= ($output ? ' ' : '').$time.' ';
                                $output .= (($time > 1 && $key == 'day') ? $key.'s' : $key);
                                $granularity--;
                        }
                        if($granularity == 0) break;
                }
                return ($output ? $output : '0 seconds').' ago';
        }
        else return date($format, $timestamp);
}

Call:

$time = timeAgo($dateRef);

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

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

Initial Title
Display dates as “time ago”

Initial Tags

                                

Initial Language
PHP