check date in range of 24 hours from now

2020-04-29 02:54发布

I have been banging my head with this for a while now. Does someone know how I can check to see if $theDate is within the range of 24 hours FROM NOW.

This is the code I have come up with but it doesn't seem to work :(

if (time() <= ($theDate + 86400)) {
    // current time is 86400 (seconds in 24 hours) or less than stored time
}

Note: $theDate is unix timestamp.

Any help would be appreciated.

Thanks :)

标签: php datetime
2条回答
▲ chillily
2楼-- · 2020-04-29 03:21

You have it backwards:

if ($theDate <= (time() + 86400)) {
    // current time is 86400 (seconds in 24 hours) or less than stored time
}
查看更多
Anthone
3楼-- · 2020-04-29 03:28

Do you always want the range to be 24 hours? Remember that there are sometimes 23 or 25 hours in a day when changing from/to DST.

A method that will take that into account is this:-

$tomorrow = (new \DateTime())->add(new \DateInterval('P1D'));
if((new \DateTime())->setTimestamp($theDate) < $tomorrow){
    //Do something
}

See the DateTime manual for more information on these very useful classes.

查看更多
登录 后发表回答