Reputation: 21988
I was working with a set of statistics for which I need to specify the start of a preceding month given any start date when I found some dates yielded unexpected results:
$theday = '2015-12-31';
for ($i = 1; $i < 6; $i++) {
echo "minus $i month = " . date('Y-m', strtotime ("-$i month" , strtotime ( $theday )) ) . '-01' . "\n";
}
Output:
minus 1 month = 2015-12-01
minus 2 month = 2015-10-01
minus 3 month = 2015-10-01
minus 4 month = 2015-08-01
minus 5 month = 2015-07-01
What did I do incorrectly there? What is the correct way to get the year and month for the month preceding date X?
Upvotes: 0
Views: 196
Reputation: 296
According to https://derickrethans.nl/obtaining-the-next-month-in-php.html, you can write "first day of -x month". The following code:
$theday = '2015-12-02';
for ($i = 1; $i < 6; $i++) {
echo "minus $i month = " . date('Y-m-d', strtotime ("first day of -$i month" , strtotime ( $theday )) ) . "\n";
}
results in:
minus 1 month = 2015-11-01
minus 2 month = 2015-10-01
minus 3 month = 2015-09-01
minus 4 month = 2015-08-01
minus 5 month = 2015-07-01
Upvotes: 1