Ah, I was wondering.
I noticed some problems when trying to use “month” years ago, and had some hope it had been worked out by now, apparently not
It seems that what I consider to be a month varies, i.e. 30 days, 31 days, 28/29 for February, from what PHP considers to be a “month”, i.e. “30 days” regardless.
That is, “month” seems to work OK most times, except for “beginnings/endings” if you know what I mean.
Perhaps it would be better to use something other than “month”?
Here is my quick test on a way to resolve this, and it seems to work, but there are a variety of solutions.
If you always need to get to the last day of the prior month, the below code works:
$today = new DateTime('2013-12-31'); // remove the date string if you want to use today's date
$todaysDate = $today->format('d'); // Get today's date, so you know how many days to subtract
$lastDayOfPriorMonth = $today->sub(new DateInterval("P{$todaysDate}D"))->format('Y-m-d'); // Outputs last day of prior month
Here is my test for the entire calendar year of 2013
<?php
$dayOfTest = new DateTime('2013-12-31');
do
{
$today = new DateTime($dayOfTest->format('Y-m-d'));
$todaysDate = $today->format('d');
echo 'Day of Test: ' . $dayOfTest->format('Y-m-d') .
'One Month Ago: ' . $today->sub(new DateInterval("P{$todaysDate}D"))->format('Y-m-d') .
'<br />';
$dayOfTest->sub(new DateInterval('P1D'));
} while ($dayOfTest->format('Y-m-d') != '2012-12-31');
Also note, you can read the “number of days within the given month” to use in the subtraction, but that won’t give you the results you want. As seen in the test below: 2013-12-01 then goes to 2013-10-31.
<?php
$dayOfTest = new DateTime('2012-12-31');
do
{
$today = new DateTime($dayOfTest->format('Y-m-d'));
$todaysDate = $today->format('t'); // line changed
echo 'Day of Test: ' . $dayOfTest->format('Y-m-d') .
'One Month Ago: ' . $today->sub(new DateInterval("P{$todaysDate}D"))->format('Y-m-d') .
'<br />';
$dayOfTest->sub(new DateInterval('P1D'));
} while ($dayOfTest->format('Y-m-d') != '2011-12-31');
Not a problem, so now you have two pieces, one that will give you the last day of the prior month and the other (which you found) gives you the 1st day of the prior month. Both seem like they may suit you just fine