PHP计算小时数

3

我有两个变量,例如:

$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

我不介意秒数,我需要的是小时和分钟。 请帮帮我 :)

0.40小时应该是24分钟,而不是40分钟。 - mario
4个回答

5
$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;

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(正确)。我在遇到的每个示例中都发现了这个问题。 - Shawn Rebelo
这里的想法是小数点前面的数字应该是小时数,小数点后面的数字应该是分钟数。由于你的时间之间有0小时7分钟,所以它应该返回0.7,而不是0.07。在我看来,这不是一个特别有用的数字,但这是原帖作者想要的... - Paul Norman

4

我喜欢使用面向对象的方法,使用DateTime类:

$from = new DateTime('13:43:13');
$to = new DateTime('18:53:13');

echo $from->diff($to)->format('%h.%i'); // 5.10

0
要不你写一个函数,把下面的代码放进去怎么样?
<?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"; 
    } 
?> 

请添加字段以接收值...

0

计算中存在缺陷。结果显示为5.2,但应该是5.02。
尝试使用09:58作为开始时间,15:00作为结束时间。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接