note 101175 added to datetime.sub

From: Date: Wed, 01 Dec 2010 02:53:18 +0000
Subject: note 101175 added to datetime.sub
Groups: php.notes 
Request: Send a blank email to php-notes+get-174504@lists.php.net to get a copy of this message
If you use diff() after sub(), the effects of the sub() will be repeated on the date object. It doesn't matter if the object is the one diffed or doing the diffing (i.e. which object you call diff() from). <?php $today = new DateTime(); $newdate = new DateTime(); print_r($newdate); $newdate->sub(new DateInterval("PT1S")); print_r($newdate); $s = $newdate->diff($today); print_r($newdate); $s = $today->diff($newdate); print_r($newdate); $s = $today->diff($newdate); print_r($newdate); ?> Prints: DateTime Object ( [date] => 2010-11-30 18:43:48 [timezone_type] => 3 [timezone] => America/Los_Angeles ) DateTime Object ( [date] => 2010-11-30 18:43:47 [timezone_type] => 3 [timezone] => America/Los_Angeles ) DateTime Object ( [date] => 2010-11-30 18:43:46 [timezone_type] => 3 [timezone] => America/Los_Angeles ) DateTime Object ( [date] => 2010-11-30 18:43:45 [timezone_type] => 3 [timezone] => America/Los_Angeles ) DateTime Object ( [date] => 2010-11-30 18:43:44 [timezone_type] => 3 [timezone] => America/Los_Angeles ) Note that using add() instead of sub() does NOT have the same effect. This is particularly undesirable -- in this example you make a datetime, use sub() to make it a relative time in the past, and then date->diff() to confirm the difference. But the diff() inadvertendly makes the difference 2x. ---- Server IP: 69.147.83.197 Probable Submitter: 174.46.204.210 ---- Manual Page -- http://www.php.net/manual/en/datetime.sub.php Edit -- https://master.php.net/note/edit/101175 Del: integrated -- https://master.php.net/note/delete/101175/integrated Del: useless -- https://master.php.net/note/delete/101175/useless Del: bad code -- https://master.php.net/note/delete/101175/bad+code Del: spam -- https://master.php.net/note/delete/101175/spam Del: non-english -- https://master.php.net/note/delete/101175/non-english Del: in docs -- https://master.php.net/note/delete/101175/in+docs Del: other reasons-- https://master.php.net/note/delete/101175 Reject -- https://master.php.net/note/reject/101175 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#174504) next »