PHP中两个DateTime之间微秒精度的差异

Jos*_*ile 7 php precision datediff

我可以通过以下解决方法在 PHP 中获得微秒的日期时间:

list($usec, $sec) = explode(" ", microtime());
echo date("Y-m-d\TH:i:s", $sec) . "." . floatval($usec)*pow(10,6);
Run Code Online (Sandbox Code Playgroud)

我需要两个日期时间之间的微秒差异,无法解决以下问题:

$datetime1 = new DateTime('2013-08-14 18:49:58.606');
$datetime2 = new DateTime('2013-08-14 22:27:19.272');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%h hours %i minutes %s seconds %u microseconds');
Run Code Online (Sandbox Code Playgroud)

DateInterval::format没有格式字符 %u 或等价的微秒。

任何人都知道解决方法吗?

Acc*_*t م 5

/**
 * returns the difference in seconds.microseconds(6 digits) format between 2 DateTime objects 
 * @param DateTime $date1
 * @param DateTime $date2
 */
function mdiff($date1, $date2){
    return number_format(abs((float)$date1->format("U.u") - (float)$date2->format("U.u")), 6);
}
Run Code Online (Sandbox Code Playgroud)


小智 4

手动创建一个具有微秒的 DateTime 对象:

$d = new DateTime("15-07-2014 18:30:00.111111");
Run Code Online (Sandbox Code Playgroud)

获取当前时间(以微秒为单位)的 DateTime 对象:

$d = date_format(new DateTime(),'d-m-Y H:i:s').substr((string)microtime(), 1, 8);
Run Code Online (Sandbox Code Playgroud)

两个 DateTime 对象之间的差异(以微秒为单位)(例如返回:2.218939)

//Returns the difference, in seconds, between two datetime objects including
//the microseconds:

function mdiff($date1, $date2){
//Absolute val of Date 1 in seconds from  (EPOCH Time) - Date 2 in seconds from (EPOCH Time)
$diff = abs(strtotime($date1->format('d-m-Y H:i:s.u'))-strtotime($date2->format('d-m-Y H:i:s.u')));

//Creates variables for the microseconds of date1 and date2
$micro1 = $date1->format("u");
$micro2 = $date2->format("u");

//Absolute difference between these micro seconds:
$micro = abs($micro1 - $micro2);

//Creates the variable that will hold the seconds (?):
$difference = $diff.".".$micro;

return $difference;
}
Run Code Online (Sandbox Code Playgroud)

本质上,它使用 strtotime 找到 DateTime 对象的差异,然后添加额外的微秒。