skip to Main Content

I am trying to compare two dates, the current time and whether it is smaller than the dates I set.
Unfortunately, the condition does not want to work in any way

function is_store_open_to_thursday($html, $product)
{
    date_default_timezone_set('Europe/Warsaw');

    $datetime1 = new DateTimeImmutable('thursday 12:00:00');
    $datetime2 = $datetime1->modify('+3 days');
    $now = time();
    $html = '<form action="' . esc_url($product->add_to_cart_url()) . '" class="cart" method="post" enctype="multipart/form-data">';
    $html .= woocommerce_quantity_input(array(), $product, false);


    if ($now >= strtotime($datetime1) && $now <= strtotime($datetime2)) {
        $html .= '<p>WORK</p>';
    }
    else{
        $html .= 'NOT WORKING';
    }

    $html .= '</form>';
    return $html;
}

2

Answers


  1. Variables $datetime1 and datetime2 are objects.
    So if you pass them to function strtotime you will should to see in your php.log file warnings:

    <b>Warning</b>: strtotime() expects parameter 1 to be string, object given in.

    Change yor conditions statement to:

    if ($now >= $datetime1->getTimestamp() && $now <= $datetime2->getTimestamp())
    
    Login or Signup to reply.
  2. It’s not very cool, but should works:

    $now = new DateTime();
    $startDate = new DateTimeImmutable("Thursday 12:00:00");
    $endDate = $startDate->modify("+3 days");
    
    if(
        ($now->format("N H:i:s") >= $startDate->format("N 12:00:00"))
        && ($now->format("N H:i:s") <= $endDate->format("N 12:00:00"))
    ) {
        echo "Date in range!";
    } else {
        echo "Date out of range!";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search