Adding one microsecond to Datetime object in PHP



PHP Snippet 1:

$date = new Datetime('2018-06-05 09:06:46.7487');
$date->modify('+1 microsecond');
echo $date->format('Y-m-d H:i:s.u');

PHP Snippet 2:

2018-06-05 09:06:46.748701

PHP Snippet 3:

$date = new Datetime('2018-06-05 09:06:46.999999');
$date->modify('+1 microsecond');
echo $date->format('Y-m-d H:i:s.u');

PHP Snippet 4:

2018-06-05 09:06:46.1000000

PHP Snippet 5:

$date = new Datetime('2018-06-05 09:06:46.7487');

// Use bcadd() to add .000001 seconds to the "microtime()" of the date
$microtime = bcadd( $date->getTimestamp().'.'.$date->format( 'u' ), '.000001', 6 );

// Reconstruct the date for consumption by __construct
$date->__construct(
    date( 'Y-m-d H:i:s.', explode( '.', $microtime )[ 0 ] ).explode( '.', $microtime )[ 1 ]
);

echo $date->format('Y-m-d H:i:s.u');

PHP Snippet 6:

2018-06-05 09:06:46.748701

PHP Snippet 7:

$date = new Datetime('2018-06-05 09:06:46.999999');

// Use bcadd() to add .000001 seconds to the "microtime()" of the date
$microtime = bcadd( $date->getTimestamp().'.'.$date->format( 'u' ), '.000001', 6 );

// Reconstruct the date for consumption by __construct
$date->__construct(
    date( 'Y-m-d H:i:s.', explode( '.', $microtime )[ 0 ] ).explode( '.', $microtime )[ 1 ]
);

echo $date->format('Y-m-d H:i:s.u');

PHP Snippet 8:

2018-06-05 09:06:47.000000