[英]Substract an amount of time to an addition of times
我必須在php中將32:30:00(字符串)減去95:05:00(字符串):
95:05:00 - 32:30:00
他們是來自額外的時間。
我找不到任何有效的代碼,因為strtotime不接受超過24的值。
請幫助我,謝謝。
例如,我已經嘗試過:
$time1 = strtotime('32:30:00');
$time2 = strtotime('95:05:00');
$difference = round(abs($time2 - $time1) / 3600,2);
echo 'différence : '.$difference;
返回0
它應該返回類似62:35:00的內容
您知道我是否可以使用moment.js或php lib嗎?
strtotime
不處理持續時間,僅處理有效時間戳。 您可以通過將時間戳分解為小時,分鍾和秒來分解時間來自己處理。 然后,您可以將它們轉換為總秒數。
<?php
$time1 = '95:05:00';
$time2 = '32:30:00';
function timeToSecs($time) {
list($h, $m, $s) = explode(':', $time);
$sec = (int) $s;
$sec += $h * 3600;
$sec += $m * 60;
return $sec;
}
$t1 = timeToSecs($time1);
$t2 = timeToSecs($time2);
$tdiff = $t1 - $t2;
echo "Difference: $tdiff seconds";
然后,我們可以將其轉換回小時和分鍾:
$start = new \DateTime("@0");
$end = new \DateTime("@$tdiff");
$interval = $end->diff($start);
$time = sprintf(
'%d:%02d:%02d',
($interval->d * 24) + $interval->h,
$interval->i,
$interval->s
);
echo $time; // 62:35:00
獲得秒數差異的一種方法是使用mktime
。
$diff = mktime(...explode(':', $time1)) - mktime(...explode(':', $time2));
有多種方法可以轉換回所需的字符串格式。 我本來建議使用sprintf
,但是其他答案已經顯示出來了,所以我不會打擾。
通常,當您處理時間間隔時,我認為以秒為單位進行所有計算然后在需要輸出結果時對其格式進行設置會更容易,因此可以避免執行此類操作。
這是另一種選擇。
$time1 = '32:30:00';
$time2 = '95:05:00';
function timeDiff($time1, $time2)
{
$time1 = explode(':', $time1);
$time2 = explode(':', $time2);
// Make sure $time2 is always the bigger time
if ($time1[0] > $time2[0]) {
$temp = $time1;
$time1 = $time2;
$time2 = $temp;
}
// Work out the difference in each of the hours, minutes and seconds
$h = abs($time2[0] - $time1[0]);
$m = abs($time2[1] - $time1[1]);
$s = abs($time2[2] - $time1[2]);
// Ensure that it doesn't say "60", since that is not convention.
$m = $m == 60 ? 0 : $m;
$s = $s == 60 ? 0 : $s;
// If minutes 'overflows', then we need to remedy that
if ($time2[1] < $time1[1]) {
$h -= $h == 0 ? $h : 1;
$m = 60 - $m;
}
// Fix for seconds
if ($time2[2] < $time1[2]) {
$m -= $m == 0 ? -59 : 1;
$s = 60 - $s;
}
// Zero pad the string to two places.
$h = substr('00'.$h, -2);
$m = substr('00'.$m, -2);
$s = substr('00'.$s, -2);
return "{$h}:{$m}:{$s}";
}
echo timeDiff($time1, $time2);
我只是分別算出每個小時,分鍾和秒之間的差異。
我對代碼進行了相應的注釋,以提供每個階段正在發生的情況的更多見解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.