Hello i need to know if this script is correct.
The goal is to send to a device a checkout if the day of checkout is equal to today.
Is my if condition is good to compare two date ?
$today = new DateTime(); // ex :20-09-2021 foreach($orders as $order){ $checkout = new Checkout(); $checkout->get($order['id']); $delivery_date = new DateTime($checkout->day); $restaurant = $checkout->getRestaurant(); //is the some date if($delivery_date->diff($today)->days === 0 ) { if (isset($restaurant->token) && !empty($restaurant->token)) { if ($popina_response = Foxorders_Popina::sendNewOrder($checkout)) { $checkout->popina_notified = 1; $checkout->popina_response = $popina_response; } if (($popina_response == '{"ok":true}') || ($popina_response == 'Shop not found') || ($popina_response == '{"error":"Shop not found"}')) { $checkout->popina_retry = 0; } $checkout->save(); } } }
Advertisement
Answer
DateTime::diff()
gives the total difference between two dates. So only when two dates are further apart than 24 hours they will be a day apart.
A better way to compare dates is:
if (($delivery_date->format('Y-m-d') == $today->format('Y-m-d')) { ..... }
This converts two DateTime
objects to strings, containing the dates, which are then compared.
Instead of $today->format('Y-m-d')
you could write: date('Y-m-d')
.