PHP — Convert milliseconds to Hours : Minutes : Seconds.fractional

AJB picture AJB · Jan 21, 2011 · Viewed 38.3k times · Source

I've got a script that takes in a value in seconds (to 2 decimal points of fractional seconds):

$seconds_input = 23.75

I then convert it to milliseconds:

$milliseconds = $seconds_input * 1000; // --> 23750

And then I want to format it like so:

H:M:S.x // --> 0:0:23.75

Where 'x' is the fraction of the second (however many places after the decimal there are).

Any help? I can't seem to wrap my mind around this. I tried using gmdate() but it kept lopping off the fractional seconds.

Thanks.

Answer

ircmaxell picture ircmaxell · Jan 21, 2011

Edit: Well, I was a bit hasty. Here's one way to do what you're asking:

function formatMilliseconds($milliseconds) {
    $seconds = floor($milliseconds / 1000);
    $minutes = floor($seconds / 60);
    $hours = floor($minutes / 60);
    $milliseconds = $milliseconds % 1000;
    $seconds = $seconds % 60;
    $minutes = $minutes % 60;

    $format = '%u:%02u:%02u.%03u';
    $time = sprintf($format, $hours, $minutes, $seconds, $milliseconds);
    return rtrim($time, '0');
}