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.


Messages In This Thread
Time Difference Function - by El Forum - 04-09-2009, 02:14 PM
Time Difference Function - by El Forum - 04-10-2009, 05:01 PM
Time Difference Function - by El Forum - 04-10-2009, 07:25 PM
Time Difference Function - by El Forum - 04-11-2009, 01:58 AM
Time Difference Function - by El Forum - 02-28-2012, 04:21 AM
Time Difference Function - by El Forum - 02-28-2012, 06:13 AM



Theme © iAndrew 2016 - Forum software by © MyBB