Hel*_*ode 10 php datetime php-7.0
我需要在PHP中向Datetime对象添加一个微秒.我试图在日期时间间隔内添加一段时间,但它不起作用.
$date = new Datetime('2018-06-05 09:06:46.7487');
$date->add(new DateInterval('PT0.00001S'));
echo $date->format('Y-m-d H:i:s.u');
Run Code Online (Sandbox Code Playgroud)
虽然我认为它应该很简单,但我无法完成它.如何将一秒的分数添加到日期时间?
如果你有PHP 7.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');
Run Code Online (Sandbox Code Playgroud)
输出:
2018-06-05 09:06:46.748701
Run Code Online (Sandbox Code Playgroud)
$date = new Datetime('2018-06-05 09:06:46.999999');
$date->modify('+1 microsecond');
echo $date->format('Y-m-d H:i:s.u');
Run Code Online (Sandbox Code Playgroud)
输出:
2018-06-05 09:06:46.1000000
Run Code Online (Sandbox Code Playgroud)
如果您有PHP 7.0或更早版本,那么您可以提取微秒并自己以"hacky"方式执行数学运算:
$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');
Run Code Online (Sandbox Code Playgroud)
输出:
2018-06-05 09:06:46.748701
Run Code Online (Sandbox Code Playgroud)
如果微秒处于,则hacky解决方案也可以工作 .999999
$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');
Run Code Online (Sandbox Code Playgroud)
输出:
2018-06-05 09:06:47.000000
Run Code Online (Sandbox Code Playgroud)