如果我有2個時間變量:數學運算
a = 00:00:12 and b = 00:00:05
如何將我加在一起,使:
c = 00:00:17 ?
然後我需要把它們劃分到箱平均, 但我堅持加入部分。
我從數據庫中的數據以這種形式,當我嘗試簡單:
c=a+b;
我得到:
00
如何在一個時間變量執行簡單的數學運算?
如果我有2個時間變量:數學運算
a = 00:00:12 and b = 00:00:05
如何將我加在一起,使:
c = 00:00:17 ?
然後我需要把它們劃分到箱平均, 但我堅持加入部分。
我從數據庫中的數據以這種形式,當我嘗試簡單:
c=a+b;
我得到:
00
如何在一個時間變量執行簡單的數學運算?
,或者你只是走直線前進;-)
<?php
$a = "00:00:12";
$b = "00:00:05";
function addTime($timeA, $timeB) {
$timeAcomponents = explode(":", $timeA);
$timeBcomponents = explode(":", $timeB);
$timeAinSeconds = $timeAcomponents[0]*60*60 + $timeAcomponents[1]*60 + $timeAcomponents[2];
$timeBinSeconds = $timeBcomponents[0]*60*60 + $timeBcomponents[1]*60 + $timeBcomponents[2];
$timeABinSeconds = $timeAinSeconds + $timeBinSeconds;
$timeABsec = $timeABinSeconds % 60;
$timeABmin = (($timeABinSeconds - $timeABsec)/60) % 60;
$timeABh = ($timeABinSeconds - $timeABsec - $timeABmin*60)/60/60;
return str_pad((int) $timeABh,2,"0",STR_PAD_LEFT).":"
.str_pad((int) $timeABmin,2,"0",STR_PAD_LEFT).":"
.str_pad((int) $timeABsec,2,"0",STR_PAD_LEFT);
}
echo "Adding time variables:\n";
echo "$a + $b = ".addTime($a, $b);
?>
在MySQL中,你可以這樣做 -
SET @a = '00:00:12';
SET @b = '00:00:05';
SET @a_sec = TIME_TO_SEC(@a);
SET @b_sec = TIME_TO_SEC(@b);
SET @c_sec = @a_sec + @b_sec;
SELECT SEC_TO_TIME(@c_sec);
+---------------------+
| SEC_TO_TIME(@c_sec) |
+---------------------+
| 00:00:17 |
+---------------------+
$date['first'] = DateTime::createFromFormat('H:i:s', "00:00:12");
$date['second'] = DateTime::createFromFormat('H:i:s', "00:00:05");
$interval = new DateInterval('PT'. $date['second']->format('s') .'S');
$date['first']->add($interval);
echo $date['first']->format('s'); // echoes 17
非常感謝你 –
不客氣,但請認爲這不是一個好的編程風格;-)這是直接的方式,這是不推薦。 N.B.'s,Devart或Ondrejs的答案更優雅。 – tamasgal