PHP-将毫秒转换为小时:分钟:Seconds.fractional

问题描述:

我有一个脚本,它可以接受以秒为单位的值(以秒为单位的2个小数点):

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

其中"x"是秒的分数(但是小数点后有很多位).

Where 'x' is the fraction of the second (however many places after the decimal there are).

有帮助吗?我似乎无法全神贯注于此.我尝试使用gmdate(),但它始终无法达到小数秒.

Any help? I can't seem to wrap my mind around this. I tried using gmdate() but it kept lopping off the fractional seconds.

谢谢.

我的想法

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" : '')
  ;
}

然后是测试

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

产生

00:00:23
00:00:23.75
00:00:23.75123456789
34293:33:09.75