如何用微秒格式化时差

时间:2016-02-09 08:09:55

标签: php time microtime

我希望得到以下两次之间的时差。时差的格式应为小时分秒,然后是微秒。我想要这种格式的最终​​答案。

$start = date(' H:i:s'.substr((string)microtime(), 1, 6));
//some code
$end = date(' H:i:s'.substr((string)microtime(), 1, 6));
//$interval = ???(end  time - start time)

1 个答案:

答案 0 :(得分:0)

这可以通过manual on microtime中的示例#2来回答:

  

示例#2 PHP 5中的时序脚本执行

<?php
$time_start = microtime(true);

// Sleep for a while
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

将此与this answer相结合,即可获得:

$time_start = microtime(true);

// Do something here that takes time ...

$time_end = microtime(true);

$time = $time_end - $time_start;
$micro = sprintf("%06d", ($time - floor($time)) * 1000000);
$dateObj = new DateTime( date("Y-m-d H:i:s.$micro", $time) );

$interval = $dateObj->format("H:i:s.u");

如果时差为1分钟,23秒和501293微秒,则 $ difference 将具有此字符串值:

  

00:01:23.501293