PHP DateTime (): displays a duration of more than 24 hours, but not like days if they are more than 24 hours

I would like to display the length of time measured in hours, minutes, and seconds, where some durations are more than 24 hours. I am currently trying:

$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 .

I prefer an object oriented solution.

Thanks:)

+6
source share
2 answers

Since you already have a length in seconds, you can simply 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 a DateTime object, here (kind of cheating):

 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 this 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; } } 
+7
source

DateTime handles time of day, not time intervals. And since there is no 25 hours, this is wrong. There DateInterval , although it handles date intervals. Use it or do a manual calculation. Even with DateInterval , although you will have to do some calculations, since it breaks the interval into several days and hours. The easiest task is to calculate what you need based on the seconds you already have.

+2
source

All Articles