php - 在 PHP 中向 Datetime 对象添加一微秒
问题描述
我需要向 PHP 中的 Datetime 对象添加微秒。我正在尝试将时间间隔添加到 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');
虽然我认为它应该很简单,但我无法完成它。如何将几分之一秒添加到日期时间?
解决方案
PHP >= 7.1 - 有效,但有一个错误!
如果您有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');
输出:
2018-06-05 09:06:46.748701
$date = new Datetime('2018-06-05 09:06:46.999999');
$date->modify('+1 microsecond');
echo $date->format('Y-m-d H:i:s.u');
输出:
2018-06-05 09:06:46.1000000
所有 PHP 版本“破解”但没有错误!
如果您有 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');
输出:
2018-06-05 09:06:46.748701
如果微秒在.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');
输出:
2018-06-05 09:06:47.000000
推荐阅读
- python-3.x - 为什么出现 Unbound Local 错误,我希望 NameError 应该在哪里引发?
- c++ - 将设置传递给模板化函数
- python - Keras 2.2.4 fit_generator 问题。值错误,向输入层输入值时出现问题
- html - 在浏览器中加载功能不会加载资源
- mysql - SQL Workbench 中的数据库设计
- ixjs - 如何从 IxJS 中的运算符管道创建自定义运算符?
- wordpress - 在 DNS 传播之前预览网站
- c++ - 数组和指针作为形式参数的区别
- javascript - 手机屏幕上的 Ng-Zorro nz-range-picker 溢出
- c - 我可以在 C 程序中制作浮点数吗?