Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

php - How to get millisecond between two dateTime obj?

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();` 

I get the error

Call to undefined method DateTime::getTimestamp()

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the strict sense, you can't.

It's because the smallest unit of time for the DateTime class is a second.

If you need a measurement containing milliseconds then use microtime()


Edit:

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;
}

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);

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...