note 87978 deleted from function.date-modify by danbrown
| From: | danbrown@php.net | Date: | Thu, 22 Sep 2011 15:53:15 +0000 |
| Subject: | note 87978 deleted from function.date-modify by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-183351@lists.php.net to get a copy of this message | ||
Note Submitter: Gijs
----
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);
}
}
?>