note 87978 added to function.date-modify

From: Date: Sun, 04 Jan 2009 11:49:02 +0000
Subject: note 87978 added to function.date-modify
Groups: php.notes 
Request: Send a blank email to php-notes+get-148789@lists.php.net to get a copy of this message
I found a rather unusual problem when using the modify function to add months to a date object. Unsure if it's bug or not, but I thought I'd post it here to warn others. When you use the modify function to add months like this: <?php $date = new DateTime(); $date->setDate(2009, 1, 31); $date->modify("+1 month"); print $date->format("Y-n-j"); ?> You will notice that the output is not 2009-2-31 but 2009-3-3. The reason for this is obvious when you look at it. Since February does not have 31 days, the object itself just counts on and sets the month to March the 3rd. However this is not what you would expect when you use it to add months in a loop, because it will skip February in this case. A fix for this is in the next block of code. It changes the day of the month to the maximum number of days of the next month when it does not fit. Can't really say it's the best solution for the problem but it does what you'd expect: <?php class DateTimeExt extends DateTime { public function modify($modify) { $match = ""; if (preg_match("/(-|\+)(\d+) months{0,1}/", $modify, $match)) { $month = ($match[1] == "-") ? $this->format("n") - $match[2] : $this->format("n") + $match[2]; $tmp = clone($this); $tmp->setDate($this->format("Y"), $month, 1); $this->setDate($this->format("Y"), $month, $this->format("j")); if ($tmp->format("n") != $this->format("n")) { $this->setDate($this->format("Y"), $tmp->format("n"), $tmp->format("t")); } } // everything else parent::modify($modify); } } ?> ---- Server IP: 83.137.20.135 Probable Submitter: 82.74.69.181 ---- Manual Page -- http://www.php.net/manual/en/function.date-modify.php Edit -- https://master.php.net/note/edit/87978 Del: integrated -- https://master.php.net/note/delete/87978/integrated Del: useless -- https://master.php.net/note/delete/87978/useless Del: bad code -- https://master.php.net/note/delete/87978/bad+code Del: spam -- https://master.php.net/note/delete/87978/spam Del: non-english -- https://master.php.net/note/delete/87978/non-english Del: in docs -- https://master.php.net/note/delete/87978/in+docs Del: other reasons-- https://master.php.net/note/delete/87978 Reject -- https://master.php.net/note/reject/87978 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#148789) next »