Reputation: 159
this code not work properly today (30-10-2017). Why?
$i = 0;
$first = strtotime('first day this month');
echo date('n', strtotime("-$i month", $first));
// return 10
$i = 1;
$first = strtotime('first day this month');
echo date('n', strtotime("-$i month", $first));
// return 10 THIS IS BAD!!!!!!
$i = 2;
$first = strtotime('first day this month');
echo date('n', strtotime("-$i month", $first));
// return 8
i want return months before $i
.
this code work properly in past days...
Upvotes: 0
Views: 316
Reputation: 17433
To clarify why this is behaving like this:
strtotime('first day this month');
This string is considered internally to be equivalent to
strtotime('1 day this month');
which is equivalent to
strtotime('+1 day');
since this month is essentially meaningless (it's always "this month").
Today, this gives us the date 2017-10-31. When we subtract one month from this, we get 2017-09-31, which is not a valid date (September only has 30 days).
Internally, when you ask for a day past the end of the month, PHP rolls over to the next month, i.e. 2017-10-01. Today (October 30th), tomorrow -1 month
actually equals the first day of the same month. You also will have run into this problem at the end of March, May and December, since they follow months with fewer days than themselves.
As mentioned in other answers, the easiest way to fix this is to add the word of, since then you'll always get the right answer.
Upvotes: 0
Reputation: 11
The incorrect syntax "first day this month" instead of "first day of this month" is interpreted as "+1 day".
So as today is 30/10/2017, "+1 day" gives 31/10/2017.
For $i=1, strtotime("-$i month", "first day this month") returns 1 month before the 31/10/2017. As 31/09/2017 does not exist, it returns the date for 01/10/2017. And so the month is still 10.
That is why it is not working as expected today, but has been working before.
Upvotes: 1
Reputation: 9396
Try the following instead:
$i = 0;
$first = strtotime('first day of this month');
echo date('n', strtotime("-$i month", $first));
// return 10
$i = 1;
$first = strtotime('first day of this month');
echo date('n', strtotime("-$i month", $first));
// return 9
$i = 2;
$first = strtotime('first day of this month');
echo date('n', strtotime("-$i month", $first));
// return 8
Added of
in the strtotime
.
Upvotes: 2