使用时“strtotime”错误 + 从 1 月开始 + 1 个月


`strtotime` bug when using + 1 month from January

我正在尝试为先前输入的日期范围制作一个带有多个选项卡的ajax日历。但例如:

我想得到下个月,它打印三月而不是二月

$start= "2013-01-31";
$current =  date('n', strtotime("+1 month",$start)) //prints 3

我认为这是因为 2014 年 2 月是 28 年,并且从开始月份开始添加 +31 这样的基数,但为什么呢?

您正在尝试在日期2013-01-31中添加一个月。它应该给出 2013 年 2 月 31 日,但由于该日期不存在,它移动到下一个有效月份(即 3 月)。

您可以使用以下解决方法:

$current = date('n', strtotime("first day of next month",strtotime($start)));

使用类DateTime

$date = new DateTime('2013-01-31');
$date->modify('first day of next month');
echo $date->format('n');

这将正确输出2 .

演示!