用格式化的时间计算时差

时间:2018-02-05 09:38:34

标签: php mysql datetime mysqli

我有两次:开始时间和持续时间。我想从开始时间中减去持续时间。我从mysql数据库读取的时间已经格式化了。我的代码:

$start= $row["start"]; //output is for e.g. 08:00:00
$dur = $row["duration"]; //output is for e.g. 01:00:00

$sub = $start - $dur; 
// I want the output to be 07:00:00
// the result now is 7 and I got an error (non well formed numeric value)

有人能帮助我吗?

3 个答案:

答案 0 :(得分:1)

或者你可以像这样实现

$date = "1970-01-01";
$start = $date." ".$row["start"];
$dur = $date ." ".$row["duration"];
$date1=date_create($start);
$date2=date_create($dur);
$diff=date_diff($date1,$date2);
echo $diff->format("%H:%I:%S");

答案 1 :(得分:0)

$start= "08:00:00";
$dur = "01:00:00";

$diff = differenceInHours($start, $dur);

echo convertTime($diff);


function differenceInHours($startdate,$enddate){
    $starttimestamp = strtotime($startdate);
    $endtimestamp = strtotime($enddate);
    $difference = abs($endtimestamp - $starttimestamp)/3600;
    return $difference;
}

function convertTime($dec)
{
    // start by converting to seconds
    $seconds = ($dec * 3600);
    // we're given hours, so let's get those the easy way
    $hours = floor($dec);
    // since we've "calculated" hours, let's remove them from the seconds variable
    $seconds -= $hours * 3600;
    // calculate minutes left
    $minutes = floor($seconds / 60);
    // remove those from seconds as well
    $seconds -= $minutes * 60;
    // return the time formatted HH:MM:SS
    return lz($hours).":".lz($minutes).":".lz($seconds);
}

// lz = leading zero
function lz($num)
{
    return (strlen($num) < 2) ? "0{$num}" : $num;
}

答案 2 :(得分:0)

您应始终以适当的格式在数据库中保存日期。而不是“已经形成”的价值。除非是非常具体的情况。

无论如何,要解决你的问题,你可以像这样做

$start = new DateTime('08:00:00');
$duration = new DateTime('01:00:00');

$interval = date_diff($start, $duration);

echo $interval->format('%H:%I:%S'); //ouput will be 07:00:00