Search code examples
phphour

Adding hours in PHP validating holidays


I have a PHP code that generates delivery date and time of an order in my system validating schedule and sundays, in this way:

<?php
$hours = 6;

$date = date('Y-m-d h:i A');
$delivery = date("d-m-Y h:i A", strtotime("+$hours hours", strtotime($fecha)));
echo $delivery;

    if (date('H') >= 18 || date('H')<9 || date('w')==0){
        $c=strtotime("tomorrow 09:00");
        $date = date("Y-m-d h:i A", $c);

        $delivery = date("d-m-Y h:i A", strtotime("+$hours hours", strtotime($fecha)));

        echo $delivery;
    }


?>

This validates if an order is made after 6pm or before 9am or if current day is Sunday, the order goes to the next day at 9am and incrementing hours. But I want to validate if current day AND the next day is Sunday or holidays like 4th July (04-07) or Xmas (25-12) to generate delivery date time in the next day of them (05-07 or 26-12).

How can I modify it?

I would like some help.


Solution

  • Just run your code in a while-loop so you can call tomorrow 09:00 as many times as necessary:

    $hours = 6;
    
    $orderPickup = time(); // Normally order should be picked up right now
    $delivery = strtotime("+$hours hours", $orderPickup);
    
    while(
        date('H', $orderPickup) > 18 
        || date('H', $orderPickup) < 9 
        || date('w', $orderPickup) == 0 // No order pickup on sunday
        || date('m-d', $orderPickup) == '12-25' // No order pickup on Christmas-day
        || date('w', $delivery) == 0) // No delivery on sunday
        || date('m-d', $delivery) == '12-25' // No delivery on Christmas-day
    ) {
        // $orderPickup will be 9 am next day
        $orderPickup = strtotime('tomorrow 9:00:00', $orderPickup);
        $delivery = strtotime("+$hours hours", $orderPickup);
    
        // If tomorrow 9:00 is stil not suitable, the while-loop will run again
    }
    echo "Delivery on " . date("d-m-Y h:i A", $delivery);