Welcome Guest, Not a member yet? Register   Sign In
Time Difference Function
#1

[eluser]Xeoncross[/eluser]
Well, after looking around the web at all the bad implementations of a simple human time difference function - I came up with this for MicroMVC. It seems to do the job well and I thought I might share it here for other to use as I thought I remembered seeing some questions about this somewhere.

Code:
/**
* Show a human-readable time difference ("10 seconds")
*
* @see                MicroMVC.com
* @param int        $from_time
* @param int        $to_time
* @return string
*/
function time_difference($from_time=0, $to_time=null) {
    
    //If not set - use current time
    if(!$to_time) { $to_time= time(); }
    
    //timestamp difference
    $difference = round(abs($to_time - $from_time));
    
    //Try seconds first
    if ($difference <= 60) {
        return $difference. ' seconds';
    }
    
    //Time Types (you can add to this)
    $times = array(
        'minute'    => 60,
        'hour'        => 60,
        'day'        => 24,
        'week'        => 7,
        'month'        => 4,
        'year'        => 12
    );
    
    
    //Try each type of time
    foreach($times as $type => $value) {
    
        //Find number of minutes
        $difference = round($difference / $value);
    
        if ($difference <= $value) {
            return $difference. ' '. $type. ($difference > 1 ? 's' : '');
        }
    }
}

I don't think it's necessary, but it's GPL in case anyone is worried about using it.
#2

[eluser]m4rw3r[/eluser]
Here is a more accurate time difference function I made:
Code:
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);
}
BSD license Wink
#3

[eluser]Xeoncross[/eluser]
And that my friend, is why I share code. Wink
#4

[eluser]Johan André[/eluser]
Hey!

Check out this:

http://ellislab.com/forums/viewthread/106557/

It depends on languagefiles too...
#5

[eluser]Unknown[/eluser]
hi....i'm new codeigniter.so plz tell me how to calculate current time in codeigniter.
plz help me
#6

[eluser]InsiteFX[/eluser]
CodeIgniter User Guide - Date Helper




Theme © iAndrew 2016 - Forum software by © MyBB