PHP Snippets
time_since
Information
(PHP Version >= 3)Functions used in this snippet: time, date, ceil, floor.
Description
str time_since( int time[, int now[, str fmt]] )
Returns the textual difference between times. If the optional now is left as NULL, the current time will be used, otherwise the time given will be used. If the optional fmt is set, the time that is returned will be formatted according to this string (assuming it is older than 2 days old, Reference www.php.net/date for how to format this).
Snippet
<?php
function time_since($time, $now=NULL, $fmt='l F jS, g:i a'){
if($now === NULL){
$now = time();
}
$diff = $now - $time;
$today = date('dmy', $now) === date('dmy', $time) ? true : false;
if($today && $diff < 60 * 60){
$num = ceil($diff / 60);
return $num . ' minute' . ($num > 1 ? 's' : '') . ' ago';
}elseif($today){
$num = floor($diff / 60 / 60);
return $num . ' hour' . ($num > 1 ? 's' : '') . ' ago';
}else{
$thisyear = date('y', $now) === date('y', $time) ? true : false;
$daydiff = date('z', $now) - date('z', $time);
if($daydiff === 1 && $thisyear){
return 'Yesterday';
}
}
return date($fmt, $time);
}
?>
Example
time_since Can be used in the following way:
<?php
echo time_since(time());
// returns something like 20 minutes ago
echo time_since('1121913694', '1121920868');
// returns 1 hour ago
echo time_since(strtotime('yesterday'));
// returns Yesterday
echo time_since(strtotime('-2 months'),NULL, 'm/d/y');
// returns something like 18/05/05
?>
Updated on Nov 4th at 4 am.
3 Responses to time_since
Good job! This saves me a lot of time.
nice. I changed it so it outputs german, and handles days, weeks, months and years, since i'm always outputting the exact date in a title-attribute. But it's the first script i found which i could modify that easily.
Thanks a bunch for this code snippet. It's greatly appreciated.