Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP date() Hours, Minutes and Seconds without leading zeros [duplicate]

Tags:

date

php

time

Possible Duplicate:
Convert seconds to Hour:Minute:Second

I've been searching all over the internet to find a good way of converting seconds into minutes:seconds without leading zeros. I already checked out this question, which is the only one I was even able to find, however none of those answers look very good. Perhaps they are the only and best way to achieve this, however I would hope not.

I have done this and it gives me the number of minutes without the leading zeros, however I am unable to get the seconds. The only way I can think of doing it this way would be to do a few lines of math and such, but that seems like an awful lot of work for something as simple as this... which I don't know why PHP doesn't have it built in for minutes and seconds anyways....

intval(gmdate("i:s", $duration));

Edit All I am trying to do is to convert the number of seconds in a video, into a H:M:S format.

like image 553
Dylan Cross Avatar asked Dec 27 '12 03:12

Dylan Cross


2 Answers

implode(
    ':',
    array_map(
        function($i) { return intval($i, 10); },
        explode(':', gmdate('H:i:s', $duration))
    )
)

however what about if hour==0 then do not print 0: and just have m:s

preg_replace(
    '~^0:~',
    '', 
    implode(
        ':',
        array_map(
            function($i) { return intval($i, 10); },
            explode(':', gmdate('H:i:s', $duration))
        )
    )
)
like image 126
zerkms Avatar answered Nov 12 '22 13:11

zerkms


I would just write it iteratively:

function duration_to_timestring($duration)
{
        $s = [];
        if ($duration > 3600) {
                $s[] = floor($duration / 3600);
                $duration %= 3600;
        }
        $s[] = floor($duration / 60);
        $s[] = floor($duration % 60);

        return join(':', $s);
}
like image 2
Ja͢ck Avatar answered Nov 12 '22 12:11

Ja͢ck