gpt4 book ai didi

DateTime 对象的 PHP 异常处理

转载 作者:可可西里 更新时间:2023-11-01 00:34:51 24 4
gpt4 key购买 nike

有人知道为什么这个函数在向它传递了一个无效日期(例如时间戳)时,尽管 try-catch 仍然抛出错误吗?

function getAge($date){
try {
$dobObject = new DateTime($date);
$nowObject = new DateTime();

$diff = $dobObject->diff($nowObject);
}

catch (Exception $e) {
echo 'Error: ', $e->getMessage();
}

return $diff->y;
}

错误:

Fatal error: Uncaught exception 'Exception' with message 'DateTime::_construct() [datetime.--construct]: Failed to parse time string (422926860) at position 7 (6): Unexpected character' in ... .php:4 Stack trace: #0 ... .php(4): DateTime->_construct('422926860') #1 ... .php(424): getAge('422926860') #2 {main} thrown in/... .php on line 4

非常感谢您!

最佳答案

Chris,你无法捕捉到 fatal error ,至少你不应该捕捉到。

引用 keparo :

PHP 不会为您提供任何捕获 fatal error 的常规方法,因为它们确实不应该被捕获。也就是说,您不应尝试从 fatal error 中恢复。匹配输出缓冲区的字符串绝对是不明智的。

如果您别无选择,请查看此帖子以获取更多信息和可能的信息 how-tos .

试试这个:

function isDateValid($str) {

if (!is_string($str)) {
return false;
}

$stamp = strtotime($str);

if (!is_numeric($stamp)) {
return false;
}

if ( checkdate(date('m', $stamp), date('d', $stamp), date('Y', $stamp)) ) {
return true;
}
return false;
}

然后:

 if isDateValid( $yourString ) {
$date = new DateTime($yourString);
}

关于DateTime 对象的 PHP 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11343403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com