PHP-将毫秒转换为小时:分钟:Seconds.fractional [英] PHP — Convert milliseconds to Hours : Minutes : Seconds.fractional

查看:808
本文介绍了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

这篇关于PHP-将毫秒转换为小时:分钟:Seconds.fractional的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆