Skip to content
Advertisement

Difference with microseconds precision between two DateTime in PHP

I can get a datetime with microseconds in PHP with a workaround as:

list($usec, $sec) = explode(" ", microtime());
echo date("Y-m-dTH:i:s", $sec) . "." . floatval($usec)*pow(10,6);

I need the difference with microseconds between two datetimes, can’t get a workaround for:

$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');

DateInterval::format doesn’t has the format character %u or equivalent for microseconds.

Anyone knows a workaround for this?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement