Milliseconds compare in php
$date1 = "2017-04-13 09:09:80:300"
$date2 = "2017-04-13 09:09:80:400"
我怎样才能检查date2
是多少少100毫秒然后$date 1
英寸和假如果不是(101 - 或多或少)
If you get your time in such format (I changed 09:09:80
to 09:09:40
as it was incorrect format)
$date1 = "2017-04-13 09:09:40:300"
$date2 = "2017-04-13 09:09:40:400"
create custom function since strtotime
doesn't support ms
function myDateToMs($str) {
list($ms, $date) = array_map('strrev', explode(":", strrev($str), 2));
$ts = strtotime($date);
if ($ts === false) {
throw new InvalidArgumentException("Wrong date format");
}
return $ts * 1000 + $ms;
}
now just check does difference is less than 100
$lessOrEqual100 = abs(myDateToMs($date1) - myDateToMs($date2)) <= 100;
Your question, while deceptively appearing simple, is actually fairly ugly, because it is the case that PHP's strtotime()
function truncates milliseconds from a timestamp. Actually, it won't even correctly process the timestamps $date1
and $date2
which you have in your question. One workaround is to trim off the millisecond portion of the timestamp, use strtotime()
to get milliseconds since the epoch, then use a regex to obtain and add the millisecond portion to this amount.
$date1 = "2017-04-13 09:09:40:300";
$date2 = "2017-04-13 09:09:40:400";
preg_match('/^.+:(d+)$/i', $date1, $matches);
$millis1 = $matches[1];
$ts1 = strtotime(substr($date1, 0, 18))*1000 + $millis1;
preg_match('/^.+:(d+)$/i', $date2, $matches);
$millis2 = $matches[1];
$ts2 = strtotime(substr($date2, 0, 18))*1000 + $millis2;
if (abs($ts1 - $ts2) < 100) {
echo "within 100 millseconds";
}
else {
echo "not within 100 millseconds";
}
Demo here:
Rextester
According to the php manual for strtotime fractions of a second are allowed, although currently ignored by the strtotime
function.
This means you could express your dates like this 2017-04-13 09:00:20.100
to have them parsed by strtotime without error (keeping them futureproofed) and then use a custom function to compare just the millisecond portion of the dates if the timestamps are the same
The below function will return true if the dates are within 100 milliseconds, false otherwise. You can pass in the amount to compare them by as an argument.
<?php
date_default_timezone_set ( "UTC" );
$date1 = "2017-04-13 09:00:20.100";
$date2 = "2017-04-13 09:00:20.300";
// pass date1, date2 and the amount to compare them by
$res = compareMilliseconds($date1,$date2,100);
var_dump($res);
function compareMilliseconds($date1,$date2,$compare_amount){
if(strtotime($date1) == strtotime($date2)){
list($throw,$milliseond1) = explode('.',$date1);
list($throw,$milliseond2) = explode('.',$date2);
return ( ($milliseond2 - $milliseond1) < $compare_amount);
}
}
?>
链接地址: http://www.djcxy.com/p/86178.html
上一篇: 是什么让JNI电话变慢?
下一篇: 毫秒比较在PHP中