由于当前月/年是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:
06001
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日.