简体   繁体   中英

php comparing timestamps within an hour +/-

I have a conditional written that compares two timestamps and I need it to execute if the time difference between the control variable and the compared variable is within 1 hour plus or minus of the compared.

it looks like this right now which is obviously only less than & equal to:

if( ($departure - $item['time']) <= 3600) ): 

would changing <= to <=> work?

This <=> operator will offer combined comparison in that it will :

Return 0 if values on either side are equal
Return 1 if value on the left is greater
Return -1 if the value on the right is greater

What you want to do instead is to compare the absolute value of $departure - $item['time']

if(abs($departure - $item['time']) <= 3600)): 

No, the <=> operator just returns a -1/0/1 when one side is smaller/equal/larger respectively, and it only works in PHP7.

It actually seems that in your case $departure - $item['time'] could go into negative values (if $item['time'] is larger than $departure ) and so your if statement will evaluate to true in cases when, say, $item['time'] is two, three or more hours in the future from $departure .

Wouldn't something like this work?

$diff = $departure - $item['time'];
if ($diff <= 3600 && $diff >= -3600)
{
    // do what you have to do
}

&& (AND) is a logical operator which means that both smaller statements must evaluate to true, in order for the complete statement to be true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM