简体   繁体   English

如何检查和比较日期范围 php

[英]How to check and compare the date range php

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;
}

Variables $datetime1 and datetime2 are objects.变量$datetime1datetime2是对象。 So if you pass them to function strtotime you will should to see in your php.log file warnings:因此,如果您将它们传递给 function strtotime您应该在 php.log 文件中看到警告:

<b>Warning</b>: strtotime() expects parameter 1 to be string, object given in . <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())

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!";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM