Unexpected date outcome for strtotime "-1 month"

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?

Answers


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

Need Your Help

Permissions not showing while installing apk

android permissions actionscript

I'm making an Android app with ActionScript using FlashBuilder. I need to use The WiFi permission for my app. The application works on desktop with no problems(AIR Desktop project). Now when I trie...