Alan Mulligan - 1 year ago 59

PHP Question

I have the below php function which takes a time argument in seconds from a database. The seconds are of type float(6,1) in the database. I then pass that value to the function below. The problem i have is if i have 1655.5 seconds i can get the hour, minutes and seconds. But how do i get the milliseconds that remain.

ie 1655.5 = 27m:35s.5ms

Thanks for any help in advance.

`<?php`

function convertTo($init)

{

$hours = ($init / 3600);

$minutes = (($init / 60) % 60);

$seconds = $init % 60;

if($minutes < 10)

{

$minutes = "0".$minutes;

}

if($seconds < 10)

{

$seconds = "0".$seconds;

}

$milli = /* code to ret the remaining milliseconds */

$stageTime = "$minutes:$seconds.$milli";

return $stageTime;

}

?>

Answer Source

Possibly slightly counter-intuitively, the easiest way would be to extract the milliseconds as the first step.

Simply `floor()`

the initial value, and subtract the result from the input. This will give you just the right-hand side of the decimal point, you can then multiply this by 1000 to give you the number of milliseconds - which you should then cast to an integer to ensure the resulting string is sensible.

```
function convertTo($init)
{
$secs = floor($init);
$milli = (int) (($init - $secs) * 1000);
$hours = ($secs / 3600);
$minutes = (($secs / 60) % 60);
$seconds = $secs % 60;
// ...
```