note 96012 added to function.date-diff
| From: | Crystark at osu1 dot php dot net | Date: | Wed, 03 Feb 2010 09:02:58 +0000 |
| Subject: | note 96012 added to function.date-diff | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-165613@lists.php.net to get a copy of this message | ||
@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;
}
----
Server IP: 195.221.21.36
Probable Submitter: 83.201.71.23
----
Manual Page -- http://www.php.net/manual/en/function.date-diff.php
Edit -- https://master.php.net/note/edit/96012
Del: integrated -- https://master.php.net/note/delete/96012/integrated
Del: useless -- https://master.php.net/note/delete/96012/useless
Del: bad code -- https://master.php.net/note/delete/96012/bad+code
Del: spam -- https://master.php.net/note/delete/96012/spam
Del: non-english -- https://master.php.net/note/delete/96012/non-english
Del: in docs -- https://master.php.net/note/delete/96012/in+docs
Del: other reasons-- https://master.php.net/note/delete/96012
Reject -- https://master.php.net/note/reject/96012
Search -- https://master.php.net/manage/user-notes.php