Skip to content
Advertisement

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.

Advertisement

Answer

My take

function formatSeconds( $seconds )
{
  $hours = 0;
  $milliseconds = str_replace( "0.", '', $seconds - floor( $seconds ) );

  if ( $seconds > 3600 )
  {
    $hours = floor( $seconds / 3600 );
  }
  $seconds = $seconds % 3600;


  return str_pad( $hours, 2, '0', STR_PAD_LEFT )
       . gmdate( ':i:s', $seconds )
       . ($milliseconds ? ".$milliseconds" : '')
  ;
}

And then the test

$testData = array(
    23,              // Seconds, w/o millis
    23.75,           // Seconds, w/millis
    23.75123456789,  // Lots of millis
    123456789.75    // Lots of seconds
);

foreach ( $testData as $seconds )
{
  echo formatSeconds( $seconds ), PHP_EOL;
}

which yields

00:00:23
00:00:23.75
00:00:23.75123456789
34293:33:09.75
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement