“ DateTime :: __ construct():无法解析时间字符串(@)”函数中的致命错误

时间:2018-08-10 18:41:27

标签: php date datetime fatal-error

我把时间花在了功能上,但是我遇到了一个我不完全理解的错误。

功能

function secondsToTime($seconds)
    {
        $dtF = new DateTime("@0");
        $dtT = new DateTime("@$seconds");

        return $dtF->diff($dtT)->format('%a Days, %h H %i M');
        // return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
    }

错误:

 PHP Fatal error:  Uncaught Exception: DateTime::__construct(): Failed
 to parse time string (@) at position 0 (@): Unexpected character in
 /home/user/public_html/Config.php:479 Stack
 trace:
 #0 /home/user/public_html/Config.php(479): DateTime->__construct('@')
 #1 /home/user/public_html/index.php(56):
 secondsToTime('')
 #2 {main}   thrown in /home/user/public_html/Config.php on line 479

什么可能导致此错误?

1 个答案:

答案 0 :(得分:1)

您在不经过任何秒数的情况下调用函数。 new DateTime("@")确实是一个错误,因为UNIX时间戳格式至少需要一位数字。

请考虑添加typehint function secondsToTime(int $seconds),因为这将确保您确实有一个数字。