我有一个场景,其中发送到
$string
的 DateTime::modify($string)
变量是从用户编辑的数据库中读取的,我如何验证 $string
是 DateTime::modify()
的正确字符串?
您可以执行类似的操作,并在将字符串传递到实际日期之前调用它:
function modifyIsValid($modifyString) {
$d = new DateTime();
$isValid = $d->modify($modifyString);
if ($isValid === false) {
return false;
}
return true;
}
如果传递的字符串无效,则->modify()
返回 false,尽管它也会抛出一个不理想的E_Warning
。
$d = new DateTime();
$string = 'not a valid modifier';
if (modifyIsValid($string)) {
// Continue
} else {
// Print a friendly error message.
}
您可以在手册中找到有关它的更多信息:http://php.net/manual/en/datetime.modify.php
希望有帮助。
通常最好的做法是在将用户输入保存到数据库之前检查用户输入,这样您就可以在退出时对其充满信心。
您也可以使用 try/catch 块:
try {
$date = new DateTime('2016-12-12');
$date->modify('+1 dayBLA');
echo $date->format('Y-m-d');
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
编辑:查看此内容后,如果传递给
modify
的字符串无效(不是我最初假设的日期字符串),您的代码将抛出 Warning
不是异常。
您可能能够触发
Warning
,暂时被视为set_error_handler
的异常。
function warning_handler($errno, $errstr, $errfile, $errline, array $errcontext) {
throwErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler('warning_handler', E_WARNING);
try {
$date = new DateTime('2016-12-12');
$date->modify('+1 daybla');
echo $date->format('Y-m-d');
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
restore_error_handler();
然而,这看起来有点令人讨厌。比较调用
modify
方法之前和之后的日期以查看它们是否不同可能会更清晰(在您的代码中,可能不是您的日志中)。
$date = new DateTime('2016-12-12');
$origDate = clone $date; //I believe this will get you an independent object
$date->modify('+1 daybla');
if ($origDate == $date) {
echo "Bad value passed to modify, probably a warning in the logs :(";
}
参加这里的聚会有点晚了,这对我来说非常适合......
function isDateModifyValid($String)
{
if (strlen($String) == 0) { return false; }
$now = new \DateTime(null, new \DateTimeZone("UTC"));
$rtn = false; // Default return value
@$now->modify($String) && $rtn = true;
// If modify($string) fails, $rtn won't set to true, else $rtn will set to true
// ^ ^ @ suppress error
return $rtn;
}
//TEST DATA
foreach (array("+1 hour", "+2 hour, -5 minutes", "12:00", "dsfv", "13:00, + 1 hour", "Yesterday, 12:00", "Neext weeekc", "Next month") as $testString)
{
if (isDateModifyValid($testString))
{
echo "VALID ::: $testString\n";
} else {
echo "INVALID ::: $testString\n";
}
}
VALID ::: +1 hour
VALID ::: +2 hour, -5 minutes
VALID ::: 12:00
INVALID ::: dsfv
VALID ::: 13:00, + 1 hour
VALID ::: Yesterday, 12:00
INVALID ::: Neext weeekc
VALID ::: Next month
为了避免触发警告,您可以使用这个简单的函数:
function isValidModify(?string $modify): bool
{
$date = new DateTime();
return (bool) @$date->modify($modify);
}
输出:
var_dump(modifyIsValid('+1 day'));
bool(true)
var_dump(modifyIsValid('xxx'));
bool(false)