note 96129 added to function.date-diff
| From: | Anonymous at osu1 dot php dot net | Date: | Wed, 10 Feb 2010 07:43:57 +0000 |
| Subject: | note 96129 added to function.date-diff | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-165821@lists.php.net to get a copy of this message | ||
The function contributed by davix on 06-Oct-2009 07:46 returns wrong results when calculating the
difference between dates that span a month boundary. It incorrectly uses the number of days in the
later month.
Simple math shows it cannot work: eg: two dates, one on January 31 and the other on February 2.
Using the function it would calculate the difference in days as 28 - 31 + 2 = -1. It should instead
be 31 - 31 + 2 = 2.
Corrected function below:
function dateDiff($d1, $d2) {
// check higher timestamp and switch if necessary
if ($d1 < $d2){
$temp = $d1;
$d1 = $d2;
$d2 = $temp;
} else {
$temp = $d2; // temp can be used for day count if required
}
$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']){
$diff['second'] = $d1['second'] - $d2['second'];
}
else {
$d1['minute']--;
$diff['second'] = 60 - $d2['second'] + $d1['second'];
}
// minutes
if ($d1['minute'] >= $d2['minute']){
$diff['minute'] = $d1['minute'] - $d2['minute'];
}
else {
$d1['hour']--;
$diff['minute'] = 60 - $d2['minute'] + $d1['minute'];
}
// hours
if ($d1['hour'] >= $d2['hour']){
$diff['hour'] = $d1['hour'] - $d2['hour'];
}
else {
$d1['day']--;
$diff['hour'] = 24 - $d2['hour'] + $d1['hour'];
}
// days
if ($d1['day'] >= $d2['day']){
$diff['day'] = $d1['day'] - $d2['day'];
}
else {
$d1['month']--;
$diff['day'] = date("t",$temp) - $d2['day'] + $d1['day'];
}
// months
if ($d1['month'] >= $d2['month']){
$diff['month'] = $d1['month'] - $d2['month'];
}
else {
$d1['year']--;
$diff['month'] = 12 - $d2['month'] + $d1['month'];
}
// years
$diff['year'] = $d1['year'] - $d2['year'];
return $diff;
}
----
Server IP: 69.147.83.197
Probable Submitter: 220.253.242.210
----
Manual Page -- http://www.php.net/manual/en/function.date-diff.php
Edit -- https://master.php.net/note/edit/96129
Del: integrated -- https://master.php.net/note/delete/96129/integrated
Del: useless -- https://master.php.net/note/delete/96129/useless
Del: bad code -- https://master.php.net/note/delete/96129/bad+code
Del: spam -- https://master.php.net/note/delete/96129/spam
Del: non-english -- https://master.php.net/note/delete/96129/non-english
Del: in docs -- https://master.php.net/note/delete/96129/in+docs
Del: other reasons-- https://master.php.net/note/delete/96129
Reject -- https://master.php.net/note/reject/96129
Search -- https://master.php.net/manage/user-notes.php