note 96012 deleted from function.date-diff by danbrown

From: Date: Wed, 03 Feb 2010 11:51:24 +0000
Subject: note 96012 deleted from function.date-diff by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-165620@lists.php.net to get a copy of this message
Note Submitter: Crystark ---- @davix $temp should be equal to $d2 (the lowest timestamp). You may currently only have a 1 day difference on most month but in february you can get 3 days difference if you compare a date in january to a date in february. here's my improved version of his script : public static function date_diff($d1, $d2=null) { if(!isset($d2)) $d2 = time(); $aDiff = array(); //check higher timestamp and switch if neccessary if ($d1 < $d2){ $aDiff['diff'] = '-'; $temp=$d1; $d1=$d2; $d2=$temp; } else $aDiff['diff'] = '+'; $temp = $d2; //NOW : $d1 > $d2 AND $temp = $d2 $aDiff['second_tot'] = $d1-$d2; $aDiff['minute_tot'] = floor($aDiff['second_tot']/60); $aDiff['hour_tot'] = floor($aDiff['minute_tot']/60); $aDiff['day_tot'] = floor($aDiff['hour_tot']/24); $d1 = date_parse(date("Y-m-d H:i:s",$d1)); $d2 = date_parse(date("Y-m-d H:i:s",$d2)); //seconds if ($d1['second'] >= $d2['second']){ $aDiff['second'] = $d1['second'] - $d2['second']; } else { $d1['minute']--; $aDiff['second'] = 60-$d2['second']+$d1['second']; } //minutes if ($d1['minute'] >= $d2['minute']){ $aDiff['minute'] = $d1['minute'] - $d2['minute']; } else { $d1['hour']--; $aDiff['minute'] = 60-$d2['minute']+$d1['minute']; } //hours if ($d1['hour'] >= $d2['hour']){ $aDiff['hour'] = $d1['hour'] - $d2['hour']; } else { $d1['day']--; $aDiff['hour'] = 24-$d2['hour']+$d1['hour']; } //days if ($d1['day'] >= $d2['day']){ $aDiff['day'] = $d1['day'] - $d2['day']; } else { $d1['month']--; $aDiff['day'] = date("t",$temp)-$d2['day']+$d1['day']; } //months if ($d1['month'] >= $d2['month']){ $aDiff['month'] = $d1['month'] - $d2['month']; } else { $d1['year']--; $aDiff['month'] = 12-$d2['month']+$d1['month']; } //years $aDiff['year'] = $d1['year'] - $d2['year']; $aDiff['month_tot'] = $aDiff['month']+($aDiff['year']*12); return $aDiff; }

« previous php.notes (#165620) next »