Difference with microseconds precision between two DateTime in PHP
/**
* 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);
}
Manually creating a DateTime object with micro seconds:
$d = new DateTime("15-07-2014 18:30:00.111111");
Getting a DateTime object of the current time with microseconds:
$d = date_format(new DateTime(),'d-m-Y H:i:s').substr((string)microtime(), 1, 8);
Difference between two DateTime objects in microseconds (e.g. returns: 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;
}
Essentially it finds the difference for the DateTime Objects using strtotime and then adding the extra microseconds on.