PHP DateTime 异常和错误处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16019126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:23:15  来源:igfitidea点击:

PHP DateTime exception and errors handling

phpdatetime

提问by Saturnix

How can I prevent PHP to crash when creating a DateTime object?

创建 DateTime 对象时如何防止 PHP 崩溃?

$in = new DateTime($in);
$out = new DateTime($out);

$inand $outboth comes from a form so they could be anything. I enforce the user to use a calendar and block it to dates with javascript. What if the user can bypass this check?

$in$out这两个来自一个表格,以便他们可以是任何东西。我强制用户使用日历并使用 javascript 将其阻止到日期。如果用户可以绕过此检查怎么办?

If $in = "anything else other than a date"PHP will crash and block the rendering of the whole page.

如果$in = "anything else other than a date"PHP 会崩溃并阻止整个页面的呈现。

How do I prevent this and just return(0)if PHP is not able to parse the date?

return(0)如果 PHP 无法解析日期,我该如何防止这种情况发生?

回答by faino

Check out the documentation on DateTime(), here's a little snippet:

查看 上的文档DateTime(),这里有一个小片段:

<?php
try {
    $date = new DateTime('2000-01-01');
} catch (Exception $e) {
    echo $e->getMessage();
    exit(1);
}

echo $date->format('Y-m-d');
?>

PHP Manual DateTime::__construct()

PHP 手册 DateTime::__construct()

回答by John Conde

strtotime()will return false if the format is bad so this shouldcatch bad formats.

strtotime()如果格式不好,将返回 false,因此这应该捕获错误的格式。

if (strtotime($in) === false)
{
     // bad format
}

回答by Agustin Meriles

What about exception handling?

异常处理呢?

try {
    $in = new DateTime($in);
} catch (Exception $e) {
    echo $e->getMessage();
    return(0);
}

回答by hek2mgl

The DateTimeconstructorwill throw an Exception if the date/time string cannot be parsed. You can catch it. Have a look at the following snippet:

如果无法解析日期/时间字符串,DateTime构造函数将抛出异常。你可以抓住它。看看下面的片段:

try   {
    $dt = new DateTime('10th - 12th June 2013'); // bad date string
} catch (Exception $e) {
    var_dump($e->getMessage());
}