note 123471 added to datetime.sub
| From: | david_newey at cable dot comcast dot com | Date: | Wed, 26 Dec 2018 18:06:13 +0000 |
| Subject: | note 123471 added to datetime.sub | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-209954@lists.php.net to get a copy of this message | ||
As noted above when subtracting months, results can be suspect. I needed to create an array of end
of month dates for 6 months starting at Oct and going back. Using:
<?php
//Instantiate array
$dateset = [];
//Create new date object
$date = new \DateTime('2018-10-31);
//Add to array
$dateset[] = $date->format('Y-m-d');
//Go back 5 months
$nbr = 6;
for($i = 1; $i < $nbr; $i++){
$date->sub(new \DateInterval('P1M'));
$dateset[] = $date->format('Y-m-d');
}
?>
Results in:
array:6 [â¼
0 => "2018-10-31"
1 => "2018-10-01"
2 => "2018-09-01"
3 => "2018-08-01"
4 => "2018-07-01"
5 => "2018-06-01"
]
However, using ->modify("last day of last month") accurately gives month ending dates:
<?php
//Instantiate array
$dateset = [];
//Create new date object
$date = new \DateTime('2018-10-31);
//Add to array
$dateset[] = $date->format('Y-m-d');
//Go back 5 months
$nbr = 6;
for($i = 1; $i < $nbr; $i++){
$date->modify('last day of last month');
$dateset[] = $date->format('Y-m-d');
}
?>
Results in:
array:6 [â¼
0 => "2018-10-31"
1 => "2018-09-30"
2 => "2018-08-31"
3 => "2018-07-31"
4 => "2018-06-30"
5 => "2018-05-31"
]
----
Server IP: 208.43.231.9
Probable Submitter: 2a01:4a0:38:1::3 (proxied: 2001:558:1422:1:e11f:2c64:89d1:8fd8)
----
Manual Page -- http://php.net/manual/en/datetime.sub.php
Edit -- https://master.php.net/note/edit/123471
Del: integrated -- https://master.php.net/note/delete/123471/integrated
Del: useless -- https://master.php.net/note/delete/123471/useless
Del: bad code -- https://master.php.net/note/delete/123471/bad+code
Del: spam -- https://master.php.net/note/delete/123471/spam
Del: non-english -- https://master.php.net/note/delete/123471/non-english
Del: in docs -- https://master.php.net/note/delete/123471/in+docs
Del: other reasons-- https://master.php.net/note/delete/123471
Reject -- https://master.php.net/note/reject/123471
Search -- https://master.php.net/manage/user-notes.php