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.
$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').
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).
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.
Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60). Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60).
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With