【问题标题】:`strtotime` bug when using + 1 month from January从一月开始使用 + 1 个月时出现“strtotime”错误
【发布时间】:2013-11-01 13:00:45
【问题描述】:

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

我想要下个月,它打印的是三月而不是二月

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

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

【问题讨论】:

  • 当你这样做时,“整个日期”(而不是一个月)是什么?好像加了31?
  • 1 月 31 日 + 1 个月 = 2 月 31 日 = 3 月 3 日(如果闰年则为 3 月 2 日)
  • 仅供参考 strtotime 将 unix 时间戳作为第二个参数 - 不是字符串。
  • 我怎样才能总是从一个日期范围中取出下个月?谢谢!

标签: php date strtotime


【解决方案1】:

您正尝试在日期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

Demo!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多