note 118342 added to datetime.add
| From: | Angelo | Date: | Thu, 19 Nov 2015 12:28:30 +0000 |
| Subject: | note 118342 added to datetime.add | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-204188@lists.php.net to get a copy of this message | ||
Another simple solution to adding a month but not autocorrecting days to the next month is this.
(Also works for substracting months)
$dt = new DateTime("2016-01-31");
$oldDay = $dt->format("d");
$dt->add(new DateInterval("P1M")); // 2016-03-02
$newDay = $dt->format("d");
if($oldDay != $newDay) {
// Check if the day is changed, if so we skipped to the next month.
// Substract days to go back to the last day of previous month.
$dt->sub(new DateInterval("P" . $newDay . "D"));
}
echo $dt->format("Y-m-d"); // 2016-02-29
Hope this helps someone.
----
Server IP: 72.52.91.14
Probable Submitter: 213.124.126.170
----
Manual Page -- http://php.net/manual/en/datetime.add.php
Edit -- https://master.php.net/note/edit/118342
Del: integrated -- https://master.php.net/note/delete/118342/integrated
Del: useless -- https://master.php.net/note/delete/118342/useless
Del: bad code -- https://master.php.net/note/delete/118342/bad+code
Del: spam -- https://master.php.net/note/delete/118342/spam
Del: non-english -- https://master.php.net/note/delete/118342/non-english
Del: in docs -- https://master.php.net/note/delete/118342/in+docs
Del: other reasons-- https://master.php.net/note/delete/118342
Reject -- https://master.php.net/note/reject/118342
Search -- https://master.php.net/manage/user-notes.php