note 94988 deleted from datetime.add by danielc
| From: | danielc@php.net | Date: | Sun, 25 Apr 2010 19:46:38 +0000 |
| Subject: | note 94988 deleted from datetime.add by danielc | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-168628@lists.php.net to get a copy of this message | ||
Note Submitter: kb at imodus dot pl
----
As noted in DateTime::modify comment The P6M sometimes gives nonintuitive results, especially for
last day of the month: 2009-05-31 + 1 month = 2009-06-31 => 2009-07-01;
To get expected behavior convert the date to first day of month , modify date, than use
't' for day in format to get last day of the month.
Example:
<?php
$f = 'Y-m-d H:i:s';
$f1 = 'Y-m-01 H:i:s';
$fL = 'Y-m-t H:i:s';
//EXPECTED
$lastDayOfTheMonth = new DateTime('2009-12-31 00:00:00');
$firstDayOfTheMonth = new DateTime($lastDayOfTheMonth->format($f1));
//echoes 2009-06-30
echo $lastDayNext6Months = $firstDayOfTheMonth->add(new
DateInterval("P6M"))->format($fL),'<br />';
//NON-EXPECTED
$lastDayOfTheMonth = new DateTime('2009-12-31 00:00:00');
//echoes 2009-07-01
echo $lastDayNext6Months = $lastDayOfTheMonth->add(new
DateInterval("P6M"))->format($f),'<br />';
?>