由于当前月份/年份是 2012 年 1 月,为什么以下代码返回 2011 年 12 月而不是 2011 年 11 月?
echo date("F Y", strtotime("-2 months"));
如果它有所不同,这是在 PHP 5.3.0 上。
最佳答案
要得到你正在寻找的东西,你可以使用这个相当冗长的版本:
echo date("F Y", strtotime("first day of this month - 2 months"));
此处详细描述了原始版本的问题:http://derickrethans.nl/obtaining-the-next-month-in-php.html .引用如下:
Over and over again PHP users complain that next month in PHP's date-string parser doesn't go to the next month, but instead skips to the one after next month; like in the following example:
<?php $d = new DateTime( '2010-01-31' ); $d->modify( 'next month' ); echo $d->format( 'F' ), "\n"; ?>
The output of the little script will be March. March obviously doesn't follow January as February is in between. However, the current behavior is correct. The following happens internally:
next month increases the month number (originally 1) by one. This makes the date 2010-02-31. The second month (February) only has 28 days in 2010, so PHP auto-corrects this by just continuing to count days from February 1st. You then end up at March 3rd. The formatting strips off the year and day, resulting in the output March. This can easily be seen when echoing the date with a full date format, which will output March 3rd, 2010:
这里是加月,减月也是一样;没有 11 月 31 日,因此 strtotime 方法将其“更正”为 12 月 1 日。
关于PHP strtotime() 没有返回正确的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9087462/