【问题标题】:Strange behaviour of PHP strtotime functionPHP strtotime 函数的奇怪行为
【发布时间】:2018-04-10 19:45:03
【问题描述】:

使用此代码:

echo strtotime("2018-03-31 -1 month");

PHP 返回日期为 2018 年 3 月 3 日,这很奇怪,这是 strtotime 的永恒错误吗?是否有一些 php 库可以提供更直观的结果?

【问题讨论】:

  • 不仅仅是strtotime,这也是:$d = new DateTime('2018-03-31'); $d->modify('-1 个月'); echo $d->format( 'Y-m-d' ), "\n";结果:2018-03-03

标签: php date


【解决方案1】:

这不是错误,但并不完全直观。

2018-03-31 减去一个月是 2 月 31 日,不存在。 PHP 的strtotime 实现通过将相关天数移到下个月来处理任何“超出范围”的日期,例如

echo date('Y-m-d', strtotime('April 31'));
// 2018-05-01

strtotime 中使用术语-1 个月 表示跳回到上个月的同一日期,然后执行上述任何必要的调整。对于 3 月 31 日,您将在 3 月 3 日结束。如果您在 1 月 31 日使用 +1 个月,您会看到同样的情况。

根据您在这种情况下实际想要发生的情况,这个问题的一些答案可能会有用:PHP: Adding months to a date, while not exceeding the last day of the month

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多