我有总小时和时间停留
$totalHours=30;
$timeSpend=13:22:00
我怎样才能找到剩余时间
$totalHours-$timeSpend
结果应该像16:38:00
如果timeSpend> $total
小时返回减去值
答案 0 :(得分:2)
您可以尝试任何一种方法。方法NR。 1很简单,但更冗长:
APPROACH NR。 1
<?php
$totalHours = 16;
$timeSpend = "13:22:00";
$baseDate = "2016-05-11";
$result = null;
$dateDiff = null;
// CONVERT BOTH $totalHours AND $timeSpend TO DATETIME OBJECTS USING AN ARBITRARY DATE AS BASE:::
// HERE WE USED THE DATE: 2016-05-11 BUT YOU CAN USE ANY DATE.
$date1 = new DateTime($baseDate);
$date2 = new DateTime($baseDate . " " . $timeSpend );
//ADD 30 HOUR TO $date1
$date1->add(new DateInterval('PT' . $totalHours . "H"));
//FIND THE DIFFERENCE BETWEEN THE 2.
$dateDiff = date_diff($date2, $date1);
// IF $date1 IS GREATER THAN $date2; SIMPLY ASSIGN THE DATE DIFFERENCE TO $dateDiff
// ELSE ASSIGN NULL TO $dateDiff
if( ($date1 > $date2) ){
$dateDiff = date_diff($date2, $date1);
//NOW FINALLY GET THE HOURS, MINUTES & SECONDS FROM THE RESULT
$hour = ($dateDiff->h < 10)? "0".$dateDiff->h : $dateDiff->h;
$min = ($dateDiff->i < 10)? "0".$dateDiff->i : $dateDiff->i;
$sec = ($dateDiff->s < 10)? "0".$dateDiff->s : $dateDiff->s;
$result = $hour . ":" . $min . ":" . $sec;
}else{
$dateDiff = null;
}
//TEST YOUR RESULT...
var_dump($result); //DUMPS '16:38:00' TO THE OUTPUT STREAM...
APPROACH NR。 2 强>
<?php
$totalHours = 30;
$timeSpend = "13:22:00";
// CONVERT BOTH $totalHours & $timeSpend TO UNIX TIMESTAMP.
$time1 = $totalHours * 60* 60;
$time2 = strtotime($timeSpend);
// CHECK IF $totalHours IS GREATER THAN $timeSpent
// IF IT IS; SUBTRACT $timeSpent FROM $totalHours
// AND ASSIGN THE DIFFERENCE TO $diff
// OTHERWISE ASSIGN NULL TO $diff
$diff = ($time1 > $time2) ? ($time1 - $time2) :null;
// NOW REFORMAT DIFF USING PHP'S date FORMATTING FUNCTION:
$diffTime = date("H:i:s", $diff);
// JUST DO SOME TESTS TO SEE YOUR RESULT DUMPED TO THE OUTPUT STREAM:
var_dump($diffTime);
答案 1 :(得分:0)
你可以减去总时数的倍数 示例
$remaining = $totalhours - $timespend;
echo $remaining;
答案 2 :(得分:0)
您应该将所有值转换为秒。因此,您可以使用此
转换您的时间$str_time = "2:50";
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$timeSeconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
然后,您可以通过乘以3600
将小时数转换为秒数$totalSeconds = $totalHours * 3600;
然后你可以从另一个中减去一个以获得剩余的秒数。
$remainingSeconds = $totalSeconds - $timeSeconds;
然后将其格式化为时间
$timeText = gmdate("H:i:s", remainingSeconds );