-
-
Save garak/1000118 to your computer and use it in GitHub Desktop.
<?php | |
// tried this today, 31 May 2011 | |
echo "\n"; | |
echo date('Y-m-d', strtotime('first day of next month')); // correct | |
echo "\n"; | |
echo date('Y-m-d', strtotime('+1 month')); // wrong! output is 2011-07-01 | |
echo "\n"; | |
echo date('Y-m-d', strtotime('next month')); // as above, output is 2011-07-01 | |
echo "\n"; | |
echo date('Y-m-d', strtotime('first day of previous month')); // correct | |
echo "\n"; | |
echo date('Y-m-d', strtotime('-1 month')); // wrong! output is 2011-05-01 | |
echo "\n"; | |
echo date('Y-m-d', strtotime('2011-05-29 first day of previous month')); // correct (nice!) |
@jakuza: I think it's not expected, at least not for everyone. If the aim of strtotime() is using natural language, "next month" and "previous month" should be clear enough: I want next (previous) month, no matter how long months are.
I agree with @garak this is strage beaviour, it breaks the intention of naturally speaking language with dates, and is not consistent
look at this example
echo date('d/m/Y', strtotime('2011-05-31 first day of +1 month')); // returns 01/06/2011
(Yes I know that first it gets the 01 of current month and then adds 1 month)
If you only need the Year and Month, this is better at skipping ahead / back by X months even on the 31st
date("M-y", mktime(0, 0, 0, date("m")-$i, 1, date("Y")));
This bug still exists in php 7.0
Thanks DazWilliams for the quick fix.
Does this still work in December when adding a month? @DazWilliams
Does this still work in December when adding a month? @DazWilliams
It sure does James.
You can see it here:
https://extendsclass.com/php-bin/e5145f2
$i=1;
echo date("M-y", mktime(0, 0, 0, 12+$i, 1, date("Y")));
Output: Jan-22
That behavior is perfectly expected when moving 1 month back/ahead from a 31-days month over 30-days month.