本文介绍了PHP DateTime异常和错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何防止创建DateTime对象时PHP崩溃?
How can I prevent PHP to crash when creating a DateTime object?
$in = new DateTime($in);
$out = new DateTime($out);
$ in
和 $ out
都来自表单,因此它们可以是任何东西。我强制用户使用日历,并使用javascript将其阻止到日期。如果用户可以绕过此检查怎么办?
$in
and $out
both 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 =除日期以外的任何内容
PHP将崩溃并阻止整个页面的呈现。
If $in = "anything else other than a date"
PHP will crash and block the rendering of the whole page.
如何防止这种情况,而只是 return(0)
如果PHP无法解析日期?
How do I prevent this and just return(0)
if PHP is not able to parse the date?
推荐答案
请查看 DateTime()
,这是一个小片段:
Check out the documentation on DateTime()
, here's a little snippet:
<?php
try {
$date = new DateTime('2000-01-01');
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
echo $date->format('Y-m-d');
?>
这篇关于PHP DateTime异常和错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!