Click to See Complete Forum and Search --> : [RESOLVED] Code audit please


zzman
10-04-2007, 02:32 PM
I wrote this simple function to get the diff between 2 dates, Is there a php function that does this better? Also can this return a wrong value for a particular date. I know it works, i just want an experts opinion cos this simple method is very critical to my app working properly. Thanks



function dateDifference($date1, $date2=null, $delimiter='/'){
if(is_null($date2)){ $date2 = date('m'.$delimiter.'d'.$delimiter.'Y'); }

$d1_arr = explode($delimiter, $date1);
$d2_arr = explode($delimiter, $date2);

if(checkdate($d1_arr['0'], $d1_arr['1'], $d1_arr['2']) && checkdate($d2_arr['0'], $d2_arr['1'], $d2_arr['2'])){
$d1_insec = mktime(0,0,0,$d1_arr['0'], $d1_arr['1'], $d1_arr['2']);
$d2_insec = mktime(0,0,0,$d2_arr['0'], $d2_arr['1'], $d2_arr['2']);

$diff['sec'] = abs($d1_insec - $d2_insec);
$diff['min'] = floor($diff['sec'] / 60);
$diff['hrs'] = floor($diff['min'] / 60);
$diff['day'] = floor($diff['hrs'] / 24);
$diff['wks'] = floor($diff['day'] / 7);
$diff['mon'] = floor(($diff['day'] / (365/12)));
$diff['yrs'] = floor($diff['day'] / 365);

return $diff;
}else{ return false; }//end if
}//end

NogDog
10-04-2007, 03:01 PM
You may get some discrepancies when the timespan between the dates crosses over a leap year situation (where there are 366 days in a year) or changes to/from daylight savings time or the occasional leap second. For a different approach, see http://www.charles-reace.com/PHP_and_MySQL/Time_Difference/. This may take a few more milliseconds to run, but it should handle the above issues better.

zzman
10-09-2007, 04:33 PM
thanks man