Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

datetime

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

I would like it to display 25:30:00.

I am looking preferably for an object oriented solution.

Thanks :)

like image 438
jcroll Avatar asked Nov 26 '12 06:11

jcroll


People also ask

What does strtotime do in PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

Why use strtotime?

The strtotime() function is a built-in function in PHP which is used to convert an English textual date-time description to a UNIX timestamp. The function accepts a string parameter in English which represents the description of date-time. For e.g., “now” refers to the current date in English date-time description.


2 Answers

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:

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

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;
    }
}
like image 193
Passerby Avatar answered Oct 22 '22 23:10

Passerby


DateTime handles time-of-day, not time intervals. And since there's no 25 o'clock, it's the wrong thing to use. There's DateInterval though, which handles date intervals. 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. The most straight forward thing to do is to calculate what you need based on the seconds you already have.

like image 22
deceze Avatar answered Oct 22 '22 22:10

deceze