我想得到下面两个时间之间的时差。时差的格式应该是小时分秒,然后是微秒。我只想要这种格式的最终答案。
$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)
这由microtime 手册中的示例 #2 回答:
Example #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"; ?>
将此与此答案结合起来,您将得到:
$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