note 92510 added to datetime.diff

From: Date: Mon, 27 Jul 2009 23:04:29 +0000
Subject: note 92510 added to datetime.diff
Groups: php.notes 
Request: Send a blank email to php-notes+get-158798@lists.php.net to get a copy of this message
WARNING: this built-in method is BROKEN. Do not use it. Whatever this method is doing internally to calculate the diff, it is simply incorrect. I have filed bug report #49081 : http://bugs.php.net/bug.php?id=49081 . <?php $jan_1 = new DateTime('2009-01-01'); $mar_31 = new DateTime('2009-03-31'); // this shows the diff as "3 months, 2 days". var_dump(date_diff($jan_1, $mar_31)); // DateTime's own add() method shows this is wrong. // outputs the correct 2009-04-03, NOT 2009-03-31 var_dump($jan_1->add(new DateInterval('P3M2D'))); ?> If you want to do the diff and get the correct "2 months, 30 days" (2009-01-01 + 2 months = 2009-03-01 + 30 days = 2009-03-31), use this diff method instead: <?php // my version, which calculates correct diffs function date_diff2 ($t1, $t2) { if (! preg_match('/^\d+\z/', $t1) && ($t1 = strtotime($t1)) === false) return false; if (! preg_match('/^\d+\z/', $t2) && ($t2 = strtotime($t2)) === false) return false; if ($t1 > $t2) list($t1, $t2) = array($t2, $t1); $diffs = array( 'years' => 0, 'months' => 0, 'days' => 0, 'hours' => 0, 'minutes' => 0, 'seconds' => 0, ); foreach (array_keys($diffs) as $interval) { while ($t2 >= ($t3 = strtotime("+1 ${interval}", $t1))) { $t1 = $t3; ++$diffs[$interval]; } } return $diffs; } // gives expected "2 months, 30 days" var_dump(date_diff2($jan_1, $mar_31)); // gives expected "2009-03-31" var_dump($jan_1->add(new DateInterval('P2M30D'))); ?> ---- Server IP: 72.55.140.6 Probable Submitter: 69.70.125.250 ---- Manual Page -- http://www.php.net/manual/en/datetime.diff.php Edit -- https://master.php.net/note/edit/92510 Del: integrated -- https://master.php.net/note/delete/92510/integrated Del: useless -- https://master.php.net/note/delete/92510/useless Del: bad code -- https://master.php.net/note/delete/92510/bad+code Del: spam -- https://master.php.net/note/delete/92510/spam Del: non-english -- https://master.php.net/note/delete/92510/non-english Del: in docs -- https://master.php.net/note/delete/92510/in+docs Del: other reasons-- https://master.php.net/note/delete/92510 Reject -- https://master.php.net/note/reject/92510 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#158798) next »