我有兩個變量,例如:PHP計算時間
$from = 13:43:13;
$to = 18:53:13;
我需要在PHP計算$from
和$to
之間的時間,使$total
將是這樣的:
$total = 5.10 // 5 hours and ten minutes
或
$total = 0.40 // 0 hours and 40 minutes
我不介意秒,我需要的是小時和分鐘。
請幫我:)
我有兩個變量,例如:PHP計算時間
$from = 13:43:13;
$to = 18:53:13;
我需要在PHP計算$from
和$to
之間的時間,使$total
將是這樣的:
$total = 5.10 // 5 hours and ten minutes
或
$total = 0.40 // 0 hours and 40 minutes
我不介意秒,我需要的是小時和分鐘。
請幫我:)
如何作出有關的函數,並把下面的代碼到你?
<?php
$from = $_REQUEST['start_time'];
$to = $_REQUEST['end_time'];
$action = $_REQUEST['action'];
?>
<?
if($action && ($action == "go")){
list($hours, $minutes) = split(':', $from);
$startTimestamp = mktime($hours, $minutes);
list($hours, $minutes) = split(':', $to);
$endTimestamp = mktime($hours, $minutes);
$seconds = $endTimestamp - $startTimestamp;
$minutes = ($seconds/60) % 60;
$hours = round($seconds/(60 * 60));
echo "Time passed: <b>$hours</b> hours and <b>$minutes</b> minutes";
}
?>
請添加字段接收值...
$from = '13:43:13';
$to = '18:53:13';
$total = strtotime($to) - strtotime($from);
$hours = floor($total/60/60);
$minutes = round(($total - ($hours * 60 * 60))/60);
echo $hours.'.'.$minutes;
也可以根據你希望它的行爲來設置分鐘... – 2012-02-01 13:12:44
09:19 - 09:12 = 0.07。不是上面代碼給出的0.7。 09:49 - 09:34 = 0.15(正確)。所以反過來,加0.7 + 0.15 = 0.85(不正確)。應該是0.07 + 0.15 = 0.22(正確)。用我遇到的每個例子來查找這個問題。 – 2015-06-11 21:23:08
這裏的想法是小數點前的數字應該是小時數,而後數應該是分鐘數。由於你的時間之間有0小時7分鐘,它應該返回0.7,而不是0.07。在我看來,這不是一個特別有用的數字,但這是OP想要的...... – 2015-06-12 10:39:31
我喜歡使用面向對象的方法,使用DateTime類:
$from = new DateTime('13:43:13');
$to = new DateTime('18:53:13');
echo $from->diff($to)->format('%h.%i'); // 5.10
'0.40'小時會是24分鐘,而不是40. – mario 2012-02-01 12:52:27