note 92510 deleted from datetime.diff by thiago

From: Date: Mon, 27 Jul 2009 23:19:43 +0000
Subject: note 92510 deleted from datetime.diff by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-158799@lists.php.net to get a copy of this message
Note Submitter: nate at mt2009 dot com ---- 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'))); ?>

« previous php.notes (#158799) next »