是否有可靠的方法来验证相对格式的DateTime::modify()的参数



PHP文档声称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是有效字符串,它们的含义是什么?

第页。S.我也看到过类似的SO问题,但在这里我已经证明了显而易见的方法并不总是有效的…

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

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等等,当然:(

最新更新