PHP date()和strtotime()在31日返回错误的月份

时间:2012-01-30 01:52:13

标签: php date strtotime

我正在使用date()strtotime()函数在下拉列表中显示接下来的3个月。

PHP代码:

   echo date("m/Y",strtotime("+0 months")); 
   echo date("m/Y",strtotime("+1 months"));
   echo date("m/Y",strtotime("+2 months")); 

但是,如果脚本在服务器日期为30日或31日时运行,则下个月(即2月)将显示为3月。 即上面的脚本应该返回

01/2012
02/2012
03/2012

但是,实际上它显示

而不是那样
01/2012
03/2012
03/2012

这是因为2月没有30或31,所以脚本将“31/02”翻译成“01/03”。

我已经阅读了php.net上的strtotime()页面,这个问题已经提出,但是没有任何有用的解决方案。那么有人可以帮我找一个解决这个问题的简单方法吗?提前谢谢!

4 个答案:

答案 0 :(得分:28)

如文档中所述,您应该将当月第一天的日期作为第二个参数传递给strtotime()函数:

$base = strtotime(date('Y-m',time()) . '-01 00:00:01');
echo date('m/Y',strtotime('+0 month', $base));
echo date('m/Y',strtotime('+1 month', $base));
echo date('m/Y',strtotime('+2 month', $base));

看到它有效:http://ideone.com/eXis9

  

01/2012

     

02/2012

     

03/2012

答案 1 :(得分:11)

尝试在你的strtotime中使用“first day of”,如下所示:

strtotime("first day of +1 month");

这将确定日期(在今天是1月30日的事件中),例如02-30(Yields march 2nd),将其转换为02-01(2月1日),然后给出正确的月份。它比其他方法更清洁,更容易记住。

答案 2 :(得分:4)

echo date('m/Y', strtotime(date('Y-m') . '-01 +2 months'));

只需将其硬编码为本月的第一天。

答案 3 :(得分:0)

不要使用strtotime()来按月获取偏移日期。它仅在PHP 5.3+中正常工作。 解决此类问题的最佳方法是使用mktime()。 以下是示例代码:

function getOffsetByMonths($nMonths, $nNow = 0) {
    if ($nNow)
        return mktime(0, 0, 0, date('n', $nNow)+ $nMonths, 1, date('Y', $nNow));
    else
        return mktime(0, 0, 0, date('n')+ $nMonths);
}
$nNow = mktime(0, 0, 0, 1, 31, 2013);
echo "Now: ". date("Y-m-d", $nNow).
"<br>(Now - 1 month): ". date("Y-m", getOffsetByMonths(-1, $nNow)). "-xx".
"<br>(Now - 2 month): ". date("Y-m", getOffsetByMonths(-2, $nNow)). "-xx".
"<br>(Now - 3 month): ". date("Y-m", getOffsetByMonths(-3, $nNow)). "-xx";