【问题标题】:Is there reliable method to validate argument for DateTime::modify() for relative format是否有可靠的方法来验证 DateTime::modify() 的相对格式的参数
【发布时间】:2018-08-06 12:42:56
【问题描述】:

PHP docs 声称 DateTime::modify()strtotime() 在出现错误时都应该返回 false,但我得到了这个:

> php -r 'var_dump(time(), strtotime("-1 week"), strtotime("-1 wesdek"), (new DateTime())->modify("-1 weeekc"));'
int(1533556632)
int(1532951832)
int(1533560232)
object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2018-08-06 11:57:12.797259"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}

> php -v
PHP 7.2.7 (cli) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

如果wesdekweeekc 是有效字符串,它们的含义是什么?

附:我见过similar SO question,但在这里我已经证明了那里的明显方法并不总是有效……

【问题讨论】:

    标签: php datetime


    【解决方案1】:

    在写这篇文章的时候,我想到了类似的东西

    function isModifyArgumentValidRelative (string $modifyString)
    {
        $now = new DateTime();
        $notNow = clone $now;
        @$modifyResult = $notNow->modify("-{$modifyString}");
        if (false === $modifyResult || $notNow == $now) {
            return false;
        }
        return true;
    }
    

    似乎它可以工作,当然除了0 seconds0 minutes 等等 :)

    【讨论】:

      猜你喜欢
      • 2015-10-12
      • 2021-07-13
      • 2022-08-24
      • 2021-07-22
      • 2016-04-26
      • 1970-01-01
      • 2015-09-05
      • 2020-12-29
      • 2015-11-07
      相关资源
      最近更新 更多