检查日期是否在 php 中的其他日期之间,而不是按应有的方式运行


Checking if a date is in between other dates in php not behaving as it should

我一直在寻找如何检查日期是否在其他日期之间,从我读到的内容来看,我可以在 php 中使用带有 date() 函数的 if 语句

我制作的函数在大多数情况下都有效,但有时它是错误的。我不知道为什么。

function checkToday($date1, $date2, $today)
{
    if($date1 < $today && $date2 > $today )
    {
        return "between";
    } elseif ($date1 < $today) {
        return "before";
    } else {
        return "after";
    }
}

我已经用许多不同的日期调用了它,除了这个之外,它们似乎都有效:

$startDate = date('d-m-Y', strtotime("07-03-2016"));
$endDate = date('d-m-Y', strtotime("19-05-2016"));
$currDate= date('d-m-Y');
$check = checkToday($startDate, $endDate, $currDate);
echo $check.' ';
echo $startDate.' ';
echo $endDate.' ';
echo $currDate.' ';

此输出: 之前 07-03-2016 19-05-2016 22-04-2016

但是,显然 22-04-2016 介于 07-03-2016 和 19-05-2016 之间

有什么想法吗?

谢谢

您正在将日期作为字符串进行比较,这就是它无法正常工作的原因。

您需要比较时间戳(由time()strtotime()返回)或使用日期时间对象。

日期时间示例:

<?php
function checkToday($date1, $date2, $today)
{    
    if( $date1 < $today && $date2 > $today )
    {
        return "between";
    } elseif ($date1 < $today) {
        return "before";
    } else {
        return "after";
    }
}
$startDate = new DateTime("2016-03-07");
$endDate = new DateTime("2016-05-19");
$currDate= new DateTime();
$check = checkToday($startDate, $endDate, $currDate);
echo $check.' '; // Returns between
echo $startDate->format("d-m-Y").' ';
echo $endDate->format("d-m-Y").' ';
echo $currDate->format("d-m-Y").' ';

php中还有一个函数strtotime。您应该使用此函数来比较 php 中的日期,如下所示

function checkToday($date1, $date2, $today)
{    
    if( strtotime($date1) < strtotime($today) && strtotime($date2) > strtotime($today) )
    {
        return "between";
    } elseif ( strtotime($date1) < strtotime($today) ) {
        return "before";
    } else {
        return "after";
    }
}