Home    Articles

 

Get passed/elapsed time with php in human readable format

 

Many times we need to display the elapsed time since a date but we don't want to show it exactly. We want it in an easly human readable format like "2 weeks ago".

For example if we have a notice 1 month,2 days and 2 hours old it is cooler to show it like "1 month ago" or if we have something 1 week and few days older it is better to show "1 week ago".

That's why a function like this is useful. 

Bellow function will display in a format includes years, months,weeks...days and even seconds.

function passedTime($date = '') {
	$time = time() - strtotime($date); // to get the time since that moment

    $tokens = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );

    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
    }
}
// how to use it
echo 'event happened '.passedTime($time).' ago';

Enjoy.

by