如何获取两个dateTime obj之间的毫秒数? [英] How to get millisecond between two dateTime obj?
问题描述
如何获取两个DateTime
对象之间的毫秒数?
How to get millisecond between two DateTime
objects?
$date = new DateTime();
$date2 = new DateTime("1990-08-07 08:44");
我尝试遵循以下评论,但出现错误.
I tried to follow the comment below, but I got an error.
$stime = new DateTime($startTime->format("d-m-Y H:i:s"));
$etime = new DateTime($endTime->format("d-m-Y H:i:s"));
$millisec = $etime->getTimestamp() - $stime->getTimestamp();`
我得到了错误
调用未定义的方法DateTime :: getTimestamp()
Call to undefined method DateTime::getTimestamp()
推荐答案
从严格意义上讲,你做不到.
In the strict sense, you can't.
这是因为DateTime类的最小时间单位是一秒钟.
It's because the smallest unit of time for the DateTime class is a second.
如果您需要一个包含毫秒的测量值,请使用 microtime()
If you need a measurement containing milliseconds then use microtime()
另一方面,如果您只是想获取两个 ISO-8601日期时间之间的间隔(以毫秒为单位)那么一个可能的解决方案是
On the other hand if you simply want to get the interval in milliseconds between two ISO-8601 datetimes then one possible solution would be
function millisecsBetween($dateOne, $dateTwo, $abs = true) {
$func = $abs ? 'abs' : 'intval';
return $func(strtotime($dateOne) - strtotime($dateTwo)) * 1000;
}
请注意,默认情况下,以上函数将返回绝对差.如果您想知道第一个日期是否早些,则将第三个参数设置为false.
Beware that by default the above function returns absolute difference. If you want to know whether the first date is earlier or not then set the third argument to false.
// Outputs 60000
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31");
// Outputs -60000 indicating that the first argument is an earlier date
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31", false);
在时间数据类型为32位的系统(例如Windows7或更早版本)上,millisecsBetween仅适用于1970-01-01 00:00:00
和2038-01-19 03:14:07
之间的日期(请参阅
On systems where the size of time datatype is 32 bits, such as Windows7 or earlier, millisecsBetween is only good for dates between 1970-01-01 00:00:00
and 2038-01-19 03:14:07
(see Year 2038 problem).
这篇关于如何获取两个dateTime obj之间的毫秒数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!