[英]How to convert microtime() to HH:MM:SS:UU
我正在测量一些卷曲请求,我使用了microtime(true)
。 示例输出将是3.1745569706
这是3.1745569706
秒。 我想将其转换为更易读的格式,比方说00:00:03:17455
(HOURS:MINUTES:SECONDS:MILLISECONDS)
$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?
从date()
上的PHP.net文章date()
类似于gmdate()
,除了在GMT中返回时间:
由于此函数只接受整数时间戳,因此只有在使用date_format()函数和使用date_create()创建的基于用户的时间戳时,u格式字符才有用。
使用这样的东西代替:
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
var。
如果你使用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);
OUTPUT
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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.