BigToach.com

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 's' '') . ' ago';
    }elseif(
$today){
        
$num floor($diff 60 60);
        return 
$num ' hour' . ($num 's' '') . ' ago';
    }else{
        
$thisyear date('y'$now) === date('y'$time) ? true false;
        
$daydiff date('z'$now) - date('z'$time);
        if(
$daydiff === && $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
?>

Added on Jul 21st at 1 am by Scott - 4 Comments
Updated on Nov 4th at 4 am.


4 Responses to time_since

v3x commented on Jan 12th at 2 am
Good job! This saves me a lot of time.
arc commented on Jun 6th at 10 am
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.
ochiba commented on Jul 18th at 2 am
Thanks a bunch for this code snippet. It's greatly appreciated.
Nikon commented on Jan 19th at 6 am
Very helpful thing, many thanks :)

Name:

Site or Mail:

Comment:

To try to reduce the ammount of spam, please enter the word GOOSE in the following form

Security Code: