计算超过24小时的PHP时间 [英] Calculate time elapsed in php - spans over 24 hours

查看:321
本文介绍了计算超过24小时的PHP时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是加上超过24小时的小时/分钟/秒,例如:

What I am trying to do is add up hours/mins/secs that span over 24 hours, for example:

12:39:25
08:22:10
11:08:50
07:33:05

我希望返回的是39:43:30,而不是从1970年开始的日期。以下是我目前使用的代码(注意 - 它在类中,不仅仅是一个功能)。

What I would like it to return is "39:43:30" rather than a date from 1970. Below is the code I'm currently using (note - its from within a class, not just a function).

private function add_time($time1, $time2)
{
$first_exploded = explode(":", $time1);
$second_exploded = explode(":", $time2);
$first_stamp = mktime($first_exploded[0],$first_exploded[1],$first_exploded[2],1,1,1970);
$second_stamp = mktime($second_exploded[0],$second_exploded[1],$second_exploded[2],1,1,1970);
$time_added = $first_stamp + $second_stamp;
$sum_time = date("H:i:s",$time_added);
return $sum_time;
}

任何建议将不胜感激。

推荐答案

这是一个很好的小功能,它将加起来在数组中传递的次数: -

Here's a nice little function that will add up any number of times passed in an array:-

function addTimes(Array $times)
{
    $total = 0;
    foreach($times as $time){
        list($hours, $minutes, $seconds) = explode(':', $time);
        $hour = (int)$hours + ((int)$minutes/60) + ((int)$seconds/3600);
        $total += $hour;
    }
    $h = floor($total);
    $total -= $h;
    $m = floor($total * 60);
    $total -= $m/60;
    $s = floor($total * 3600);
    return "$h:$m:$s";
}

使用如下: -

$times = array('12:39:25', '08:22:10', '11:08:50', '07:33:05',);
var_dump(addTimes($times));

输出: -

string '39:43:30' (length=8)

这篇关于计算超过24小时的PHP时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆