note 116227 added to datetime.add
| From: | patrick dot mckay7 at gmail dot com | Date: | Tue, 25 Nov 2014 16:34:35 +0000 |
| Subject: | note 116227 added to datetime.add | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-201019@lists.php.net to get a copy of this message | ||
Here is a solution to adding months when you want 2014-10-31 to become 2014-11-30 instead of
2014-12-01.
<?php
/**
* Class MyDateTime
*
* Extends DateTime to include a sensible addMonth method.
*
* This class provides a method that will increment the month, and
* if the day is greater than the last day in the new month, it
* changes the day to the last day of that month. For example,
* If you add one month to 2014-10-31 using DateTime::add, the
* result is 2014-12-01. Using MyDateTime::addMonth the result is
* 2014-11-30.
*/
class MyDateTime extends DateTime
{
public function addMonth($num = 1)
{
$date = $this->format('Y-n-j');
list($y, $m, $d) = explode('-', $date);
$m += $num;
while ($m > 12)
{
$m -= 12;
$y++;
}
$last_day = date('t', strtotime("$y-$m-1"));
if ($d > $last_day)
{
$d = $last_day;
}
$this->setDate($y, $m, $d);
}
}
?>
----
Server IP: 72.52.91.14
Probable Submitter: 173.164.31.73
----
Manual Page -- http://php.net/manual/en/datetime.add.php
Edit -- https://master.php.net/note/edit/116227
Del: integrated -- https://master.php.net/note/delete/116227/integrated
Del: useless -- https://master.php.net/note/delete/116227/useless
Del: bad code -- https://master.php.net/note/delete/116227/bad+code
Del: spam -- https://master.php.net/note/delete/116227/spam
Del: non-english -- https://master.php.net/note/delete/116227/non-english
Del: in docs -- https://master.php.net/note/delete/116227/in+docs
Del: other reasons-- https://master.php.net/note/delete/116227
Reject -- https://master.php.net/note/reject/116227
Search -- https://master.php.net/manage/user-notes.php