8

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

list($usec, $sec) = explode(" ", microtime());
echo date("Y-m-d\TH: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?

Jose Nobile
  • 3,243
  • 4
  • 23
  • 30
  • 1
    `DateInterval` does not support microseconds. And also `DateTime` does not support them. All points that you have to do all related calculations manually to achieve such precision. – baldrs Aug 15 '13 at 15:55
  • 1
    DateTime::createFromFormat() added the `u` format fairly recently (PHP 5.5?), though I can't find any evidence that it's supported by DAteInterval – Mark Baker Aug 15 '13 at 16:02
  • @Baldrs I know, but with time functions is easy to make errors, I'm asking for a workaround, a non standard solution. – Jose Nobile Aug 15 '13 at 19:29
  • @MarkBaker I'm using PHP 5.5.1 %u is printed as such – Jose Nobile Aug 15 '13 at 19:31
  • Do you expect the same format as Y-m-d H:i:s.(microseconds)? Then you can get microseconds using a regex, calculate difference between them manually and insert it inside format string. – baldrs Aug 16 '13 at 08:19
  • 2
    For reference, PHP 7.1 has added `F` and `f` for microseconds (with and without leading zeroes respectively) to `DateInterval::format`. – rpkamp Feb 06 '18 at 12:02

6 Answers6

6
/**
 * 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);
}
Accountant م
  • 6,975
  • 3
  • 41
  • 61
4

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.

  • Why are you using strtotime($date1->format('d-m-Y H:i:s.u')) instead of strtotime($date1->format('d-m-Y H:i:s'))? – Mykola Vasilaki Jul 28 '15 at 18:48
  • I guess it doesn't make a difference as the u value will always be the same –  Jul 31 '15 at 11:06
  • your code have bug, for these data: 2021-01-27 11:56:19.198768 and 2021-01-27 11:56:20.199023 , return 1.255 , but correction was: 1.000255 – Nabi K.A.Z. Jan 27 '21 at 08:27
2

Since PHP 7.1 (2016-12-01) there is %f and %F for microseconds precision, but just from 7.2 (2017-11-30) it is safe to use due to the critical date bugs in 7.1 (Tested)

The working example:

<?php
$datetime1 = new DateTime('2013-08-14 18:49:58.800');
$datetime2 = new DateTime('2013-08-14 22:27:19.900');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%h hours %i minutes %s seconds %f microseconds');

PD: Answering my own question posted 4 years before the existence of %f

Jose Nobile
  • 3,243
  • 4
  • 23
  • 30
0

I had to replace this

$micro = abs($micro1 - $micro2);

with this

str_pad(abs($micro1 - $micro2), 6, '0', STR_PAD_LEFT);

to get the correct microtime for some reason.

slfan
  • 8,950
  • 115
  • 65
  • 78
0
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");

  //Difference between these micro seconds:
  $diffmicro = $micro1 - $micro2;

  list($sec,$micro) = explode('.',((($diff) * 1000000) + $diffmicro )/1000000);

  //Creates the variable that will hold the seconds (?):
  $difference = $sec . "." . str_pad($micro,6,'0');

  return $difference;
}

This function returns the correct difference

Example:
    Start:"2016-10-27 17:17:52.576801"
    End:"2016-10-27 17:18:00.385801"
    Difference:"7.809000"

    Old Function:
    Difference:"8.191000"
Ajean
  • 5,528
  • 14
  • 46
  • 69
  • your code have bug, for these data: 2021-01-27 11:56:19.198768 and 2021-01-27 11:56:20.199023 , return 0.998759 , but correction was: 1.000255 – Nabi K.A.Z. Jan 27 '21 at 08:32
0

Shorter version with float returned

function diff(\DateTimeInterface $a, \DateTimeInterface $b): float
{
    return ($a->getTimestamp() - $b->getTimestamp()) + ($a->format("u") - $b->format("u")) / 1000000;
}
wtorsi
  • 692
  • 2
  • 8
  • 27
  • for these data: 2021-01-27 11:56:19.198768 and 2021-01-27 11:56:20.199023 , return -1.000255 , I thinks better return positive number. – Nabi K.A.Z. Jan 27 '21 at 08:33