Mohammad
Mohammad

Reputation: 142

PHP add miliseconds as microtime to date

This is my code:

$d2 = new DateTime("2019-01-01 02:24:19.769002");
echo $d2->format("Y-m-d H:i:s.u");

$tBefore = microtime(true);

// GET ANOTHER DATA

$tAfter = microtime(true);

$d2->modify('+'.($tAfter-$tBefore).' microsecond');
echo $d2->format("Y-m-d H:i:s.u");

But my code return wrong date for milliseconds.

I want to add seconds with milliseconds to first date and get times of ANOTHER DATA.

Actually if ANOTHER DATA take 0.100 milliseconds, my result should be 2019-01-01 02:24:19.869002

Upvotes: 0

Views: 196

Answers (2)

jspit
jspit

Reputation: 7703

As of PHP 7.1, microseconds can also be easily added to DateTime using the modify method. The microsecond value must be an integer and cannot be a float. microtime (true) also delivers seconds as float and not microseconds.

$date = new DateTime("2019-01-01 02:24:19.769002");
$seconds = 0.100;

$intMicroseconds = intval($seconds * 1000000);
$date->modify($intMicroseconds.' microseconds');

echo $date->format("Y-m-d H:i:s.u");
//2019-01-01 02:24:19.869002

Upvotes: 1

Shane
Shane

Reputation: 1230

You can use DateTime and DateInterval:

<?php

$d2 = new DateTime('2019-01-01 02:24:19.769002');

$tBefore = new DateTime();
// `sleep` to simulate work done between `$tBefore` and `$tAfter`
sleep(1);
$tAfter = new DateTime();

$d2->add($tBefore->diff($tAfter));

print_r($d2);

https://www.php.net/manual/en/class.dateinterval.php

https://www.php.net/manual/en/datetime.add

https://www.php.net/manual/en/datetime.diff

Upvotes: 1

Related Questions