我有一个PHP DateTime对象,其创建的微秒如下:
$time = microtime(true);
$microseconds = sprintf('%06d', ($time - floor($time)) * 1000000);
$dt = new DateTime(date('Y-m-d H:i:s.' . $microseconds, $time));
Run Code Online (Sandbox Code Playgroud)
如何在$dt不创建全新DateTime实例的情况下修改微秒值?
这似乎自 7.1.0-rc4以来可用
$dt = new DateTime('2020-01-01 0:00');
$dt->modify('+500 ms');
Run Code Online (Sandbox Code Playgroud)
但是在 PHP 手册中找不到它。
小智 5
手动创建一个具有微秒的 DateTime 对象:
$d = new DateTime("15-07-2014 18:30:00.111111");
Run Code Online (Sandbox Code Playgroud)
获取当前时间(以微秒为单位)的 DateTime 对象:
$d = date_format(new DateTime(),'d-m-Y H:i:s').substr((string)microtime(), 1, 8);
Run Code Online (Sandbox Code Playgroud)
两个 DateTime 对象之间的差异(以微秒为单位)(例如返回:2.218939)
//Returns the difference, in seconds, between two datetime objects including
//the microseconds:
function mdiff($date1, $date2){
$date1sec = strtotime($date1->format('d-m-Y H:i:s.u'));
$date2sec = strtotime($date2->format('d-m-Y H:i:s.u'));
//Absolute val of Date 1 in seconds from (EPOCH Time) - Date 2 in seconds from (EPOCH Time)
$secdiff = abs($date1sec-$date2sec);
//Creates variables for the microseconds of date1 and date2
$micro1 = $date1->format("u");
$micro2 = $date2->format("u");
if (($date1sec<$date2sec && $micro1>$micro2)||($date1sec>$date2sec && $micro1<$micro2)){
$microdiff = abs(1000000 - abs($micro1-$micro2));
$secdiff = $secdiff - 1;
} else {
$microdiff = abs($micro1 - $micro2);
}
//Creates the variable that will hold the seconds (?):
$difference = $secdiff.".".$microdiff;
return $difference;
}
Run Code Online (Sandbox Code Playgroud)
本质上,它使用 strtotime 找到 DateTime 对象的差异,然后添加额外的微秒。
您需要我创建添加和子项吗?
| 归档时间: |
|
| 查看次数: |
4291 次 |
| 最近记录: |