我测量了一些卷曲请求,并使用了microtime(true)
。示例输出为3.1745569706
这是3.1745569706
秒。我想把它转换成一种可读性更强的格式,比如00:00:03:17455
(小时:分钟:秒:毫秒(
$maxWaitTime = '3.1745569706';
echo gmdate("H:i:s.u", $maxWaitTime);
// which returns
00:00:01.000000
echo date("H:i:s.u" , $maxWaitTime)
// which returns
18:00:01.000000
这看起来不对。我不太确定我在这里错过了什么。
如何将microtime((转换为HH:MM:SS:UU?
来自PHP.net关于date()
的文章,与gmdate()
类似,只是时间以GMT:返回
由于此函数只接受整数时间戳,因此u格式只有在将date_format((函数与使用date_create((创建的基于用户的时间戳。
用这样的东西代替:
list($usec, $sec) = explode(' ', microtime()); //split the microtime on space
//with two tokens $usec and $sec
$usec = str_replace("0.", ".", $usec); //remove the leading '0.' from usec
print date('H:i:s', $sec) . $usec; //appends the decimal portion of seconds
打印:00:00:03.1745569706
如果您愿意,可以使用round()
对$usec
变量进行更多的舍入。
如果您使用microtime(true)
,请使用以下内容:
list($sec, $usec) = explode('.', microtime(true)); //split the microtime on .
<?php
function format_period($seconds_input)
{
$hours = (int)($minutes = (int)($seconds = (int)($milliseconds = (int)($seconds_input * 1000)) / 1000) / 60) / 60;
return $hours.':'.($minutes%60).':'.($seconds%60).(($milliseconds===0)?'':'.'.rtrim($milliseconds%1000, '0'));
}
echo format_period(3.1745569706);
输出
0:0:3.174
假设人们真的关心微秒,这是公认的罕见现象,那么就不应该使用任何涉及浮点的表示。
相反,使用gettimeofday((,它将返回一个关联数组,该数组包含整数形式的秒和微秒。
$g1 = gettimeofday();
# execute your process here
$g2 = gettimeofday();
$borrow = $g2['usec'] < $g1['usec'] ;
$seconds = $g2['sec'] - $g1['sec'] - $borrow ;
$micros = $borrow*1000000 + $g2['usec'] - $g1['usec'] ;
$delta = gmdate( 'H:i:s.', $seconds ).sprintf( '%06d', $micros );