简体   繁体   中英

Multiple Operators in PHP If Statement

Just wanted to double check and make sure my line of thinking is correct. This hook runs every 48 hours, so I need to check if an event is happening today or tomorrow.

 $now = date('Y/m/d');
$today = explode("/", $now);

The event start date has the same format, but the value varies, and is stored the same way.

if ( $today[1] == $eventDate[1] &&
(intval($today[2]) == (intval($eventDate[2]-1)) || (intval($today[2]) == intval($eventDate[2])-2))) {

//run code

}

In my opinion, you should consider to work with DateTime objects :

$today = new \DateTime();
$eventDateTime = \DateTime::createFromFormat('Y/m/d', $eventDate);

if ($today->format('d-m-Y') === $eventDateTime->format('d-m-Y')) {
    ...
}

If you want to check that an event is happening today or tomorrow, you could do like this :

$start = new \DateTime();
$start->setTime(0,0,0);
$end = new \DateTime();
$end->add(new \DateInterval('P1D'));
$end->setTime(23,59,59);
$eventDateTime = \DateTime::createFromFormat('Y/m/d', $eventDate);

if ($eventDateTime >= $start && $eventDateTime <= $end) {
    ...
}

This way you check if a date is in a certain period. Here I added 1 day to the current date but you can adapt the code and set more than 1 day if you want.

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