Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 428
AJB Avatar asked Jan 21 '11 20:01

AJB


People also ask

How to convert milliseconds to hours in php?

$input = "23.75"; $seconds = floor($input); $date = DateTime::createFromFormat('s', floor($seconds)); $ms = ($input-$seconds); if($ms == 0) { $ms = ""; } else { $ms = ltrim($ms,"0,"); } echo $date->format('H:i:s').

How convert seconds to hours minutes and seconds in PHP?

php function convert_seconds($seconds) { $dt1 = new DateTime("@0"); $dt2 = new DateTime("@$seconds"); return $dt1->diff($dt2)->format('%a days, %h hours, %i minutes and %s seconds'); } echo convert_seconds(200000).

How to convert milliseconds to seconds in php?

Instead, you will probably just want to do some simple maths: $input = 70135; $uSec = $input % 1000; $input = floor($input / 1000); $seconds = $input % 60; $input = floor($input / 60); $minutes = $input % 60; $input = floor($input / 60); // and so on, for as long as you require.

How do you convert milliseconds to seconds?

Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60). Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60).


1 Answers

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');
}
like image 136
ircmaxell Avatar answered Sep 23 '22 02:09

ircmaxell