Wednesday, June 18, 2008

Calculate date or time difference.

Function to calculate date or time difference.

<?php
/**
* Function to calculate date or time difference. Returns an array or
* false on error.
*
* @author MFJ <faisal.hexa@gmail.com>
* @copyright Copyright &copy; 2007, MFJ
* @link http://www.gidnetwork.com/b-16.html Get the date / time difference with PHP
* @param string $start
* @param string $end
* @return array
*/
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 );
}
?>

No comments: