简体   繁体   English

PHP DateTime():显示大于24小时的时间长度,但如果超过24小时则不显示天数

[英]PHP DateTime(): Display a length of time greater than 24 hours but not as days if greater than 24 hours

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. 我想显示以小时,分钟和秒为单位测量的时间长度,其中一些时间长度大于24小时。 Currently I am trying this: 目前我正在尝试这个:

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

I would like it to display 25:30:00 . 我希望它显示25:30:00

I am looking preferably for an object oriented solution. 我正在寻找一个面向对象的解决方案。

Thanks :) 谢谢 :)

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"

If you really want to use DateTime object, here's a (kind of cheating) solution: 如果你真的想使用DateTime对象,这里有一种(作弊)解决方案:

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

If you need it OO and don't mind creating your own class, you can try 如果您需要OO并且不介意创建自己的类,您可以尝试

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;
    }
}

DateTime handles time-of-day, not time intervals. DateTime处理时间,而不是时间间隔。 And since there's no 25 o'clock, it's the wrong thing to use. 由于没有25点,使用它是错误的。 There's DateInterval though, which handles date intervals. 但是有DateInterval ,它处理日期间隔。 Use it or do some manual calculation. 使用它或进行一些手动计算。 Even with DateInterval though you'll have to do some calculations, since it'll break down an interval into days and hours. 即使使用DateInterval你也必须做一些计算,因为它会将间隔分解为几天和几小时。 The most straight forward thing to do is to calculate what you need based on the seconds you already have. 最直接的事情是根据你已经拥有的秒数来计算你需要的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM