如果至少一次大于24小时,php DateTime()diff会返回致命错误

时间:2018-02-25 12:44:19

标签: php mysql datetime

有一些脚本,用于计算用户在比赛中花费的时间。并且不需要任何日期,时间或天数,只是H:i:s返回..

Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (25:46:10) at position 0 (2): Unexpected character' in

它完美无缺,直到我得到一名赛车手在比赛中花了超过25小时......然后得到datetime()

我还读到日期时间计算到24小时间隔。所以现在寻找解决方案来计算它而不是sendhello

1 个答案:

答案 0 :(得分:0)

通过编写两个新函数来找出我的解决方案

function secToTime($seconds){
    $hours = floor($seconds / 3600);
    $mins = floor($seconds / 60 % 60);
    $secs = floor($seconds % 60);

    $time_format = sprintf('%02d:%02d:%02d', $hours, $mins, $secs);

    return $time_format;
}

function timeToSec($time){
    $str_time = $time;

    sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);

    $time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;

    return $time_seconds;
}

并像这样使用它们:

$time1 = timeToSec($val -> total_time_spent);
$time2 = timeToSec($first_place_time);
$diff = secToTime($time1 - $time2);

它完美运作