Alan Mulligan
Alan Mulligan

Reputation: 1198

Convert seconds(float) into mm:ss:ms in php

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;
    }

?>

Upvotes: 3

Views: 4962

Answers (2)

Faisal
Faisal

Reputation: 4765

I have updated this function with Leading Zero. Now time will be shown like 00:00:00. I am using this one in my google analytics project it's working perfectly. I hope this may help someone else.

<?php
function convertTo($init)
{
    $init  = number_format($init, 2);
    $secs  = floor($init);
    $milli = (int) (($init - $secs) * 1000);
    $milli = str_pad($milli, 2, '0', STR_PAD_LEFT);
    ;
    $hours   = ($secs / 3600);
    $minutes = (($secs / 60) % 60);
    $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
    $seconds = $secs % 60;
    $seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);
    if ($hours > 1) {
        $hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
    } else {
        $hours = '00';
    }
    $Time = "$hours:$minutes:$seconds";
    return $Time;
}

?>

Upvotes: 1

DaveRandom
DaveRandom

Reputation: 88647

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;
      // ...

Upvotes: 4

Related Questions