laarsk
laarsk

Reputation: 872

php - get time difference

I am using a php script to calculate the time difference between two given times, which you can find here: http://www.gidnetwork.com/b-16.html

I just figured out that script has a bug: when the start time is before midnight [lets say 22:30] and the end time is after midnight [lets say 00:30] the function won't work.

Can you help me fix that? This is the script used:

    function get_time_difference( $start, $end )
{
    $uts['start']      =    strtotime( $start );
    $uts['end']        =    strtotime( $end );
    if( $uts['start']!==-1 && $uts['end']!==-1 )
    {
        if( $uts['end'] >= $uts['start'] )
        {
            $diff    =    $uts['end'] - $uts['start'];
            if( $days=intval((floor($diff/86400))) )
                $diff = $diff % 86400;
            if( $hours=intval((floor($diff/3600))) )
                $diff = $diff % 3600;
            if( $minutes=intval((floor($diff/60))) )
                $diff = $diff % 60;
            $diff    =    intval( $diff );            
            return( array('days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
        }
        else
        {
            trigger_error( "Ending date/time is earlier than the start date/time", E_USER_WARNING );
        }
    }
    else
    {
        trigger_error( "Invalid date/time data detected", E_USER_WARNING );
    }
    return( false );
}

Upvotes: 2

Views: 1710

Answers (1)

matino
matino

Reputation: 17715

Why not use getdate() function instead? You'll be sure then that your code works, whatever you mean by saying it "won't work".

function get_time_difference($start, $end)
{
    $uts['start']      =    strtotime($start);
    $uts['end']        =    strtotime($end);
    if ($uts['start'] !==-1 && $uts['end'] !==-1)
    {
        if( $uts['end'] >= $uts['start'] )
        {     
            return getdate($uts['end'] - $uts['start']);
        }
        else
        {
            trigger_error("Ending date/time is earlier than the start date/time", E_USER_WARNING);
        }
    }
    else
    {
        trigger_error("Invalid date/time data detected", E_USER_WARNING);
    }
    return(false);
}

Upvotes: 2

Related Questions