DevHow: Code Snippets from all around

PHP Time Difference Function

URL: http://codeigniter.com/forums/viewthread/111248/

Tag(s): PHP

A function that returns time difference in readable format from two timestamps.

function time_diff($from, $to)
{
    $diff = abs($from - $to);
    
    $units = array('year' => 31557600, 'month' => 2635200, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'minute' => 60, 'second' => 1);
    
    $str = '';
    foreach($units as $title => $length)
    {
        if($d = floor($diff / $length))
        {
            $str[] = $d . ' ' . $title . ($d > 1 ? 's' : '');
            
            $diff -= $length * $d;
        }
    }
    
    return implode(' ', $str);
}

Comments

You must be logged in to comment