PHP DateTime():显示大于24小时的时间长度,但不得超过24小时 [英] PHP DateTime(): Display a length of time greater than 24 hours but not as days if greater than 24 hours

查看:299
本文介绍了PHP DateTime():显示大于24小时的时间长度,但不得超过24小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示一段时间,以小时,分钟和秒为单位,其中一段时间​​长于24小时。目前我正在尝试:

I would like to display a length of time measured in hours, minutes and seconds where some lengths of time are greater than 24 hours. Currently I am trying this:

$timeLength = new DateTime();
$timeLength->setTime(25, 30);
echo $timeLength->format('H:m:i'); // 01:30:00

我希望显示 25: 30:00

我正在寻找面向对象的解决方案。

I am looking preferably for an object oriented solution.

谢谢:)

推荐答案

由于你已经有几秒钟的长度,你可以计算它:

Since you already have the length in seconds, you can just calculate it:

function timeLength($sec)
{
    $s=$sec % 60;
    $m=(($sec-$s) / 60) % 60;
    $h=floor($sec / 3600);
    return $h.":".substr("0".$m,-2).":".substr("0".$s,-2);
}
echo timeLength(6534293); //outputs "1815:04:53"

如果你真的想使用 DateTime 对象,这是一种(一种欺骗)解决方案:

If you really want to use DateTime object, here's a (kind of cheating) solution:

function dtLength($sec)
{
    $t=new DateTime("@".$sec);
    $r=new DateTime("@0");
    $i=$t->diff($r);
    $h=intval($i->format("%a"))*24+intval($i->format("%H"));
    return $h.":".$i->format("%I:%S");
}
echo dtLength(6534293); //outputs "1815:04:53" too

如果你需要它OO,不介意创建自己的课程,你可以尝试

If you need it OO and don't mind creating your own class, you can try

class DTInterval
{
    private $sec=0;
    function __construct($s){$this->sec=$sec;}
    function formet($format)
    {
        /*$h=...,$m=...,$s=...*/
        $rst=str_replace("H",$h,$format);/*etc.etc.*/
        return $rst;
    }
}

这篇关于PHP DateTime():显示大于24小时的时间长度,但不得超过24小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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