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

jcr*_*oll 6 php datetime

我想显示以小时,分钟和秒为单位测量的时间长度,其中一些时间长度大于24小时.目前我正在尝试这个:

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

我希望它能显示出来25:30:00.

我正在寻找一个面向对象的解决方案.

谢谢 :)

Pas*_*rby 7

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

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"
Run Code Online (Sandbox Code Playgroud)

如果你真的想使用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
Run Code Online (Sandbox Code Playgroud)

如果您需要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;
    }
}
Run Code Online (Sandbox Code Playgroud)