Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify microseconds of a PHP DateTime object

Tags:

php

datetime

I have a PHP DateTime object with microseconds created as follows:

$time = microtime(true);
$microseconds = sprintf('%06d', ($time - floor($time)) * 1000000);

$dt = new DateTime(date('Y-m-d H:i:s.' . $microseconds, $time));

How can I modify the microseconds value of $dt, without creating a completely new DateTime instance?

like image 366
Tim Avatar asked Feb 13 '14 14:02

Tim


3 Answers

This seems to have been available since 7.1.0-rc4

$dt = new DateTime('2020-01-01 0:00');
$dt->modify('+500 ms'); // Milliseconds.
$dt->modify('+123456 usec'); // Microseconds.
$dt->modify('+123456 microseconds'); // This works too.

Can't find it in the PHP manual though.

like image 162
aross Avatar answered Oct 14 '22 08:10

aross


You can't.

There are three methods that can modify the value of a DateTime instance: add, sub and modify. We can rule out add and sub immediately because they work in terms of a DateInterval which does not have sub-second precision.

modify accepts a string in one of the standard recognized formats. Of those formats, only the relative ones are of interest here because the other ones work in an absolute manner; and there is no relative format that allows tweaking the msec part (that unit is not recognized).

like image 36
Jon Avatar answered Oct 14 '22 07:10

Jon


as of PHP 7.1 DateTime::setTime() supports microseconds.

like image 36
Max Avatar answered Oct 14 '22 09:10

Max