PHP 检查日期是否介于两个日期之间

2022-08-30 08:09:13

我从Stackoverflow获得了这段代码,并对其进行了轻微的更改,以配合今天的日期。

我想检查今天是否适合两个日期。但这是行不通的。我错过了什么?

$paymentDate = date('d/m/Y');
echo $paymentDate; // echos today! 
$contractDateBegin = date('d/m/Y', '01/01/2001');
$contractDateEnd = date('d/m/Y', '01/01/2015');

if ($paymentDate > $contractDateBegin && $paymentDate < $contractDateEnd)
{
  echo "is between";
}
else
{
echo "NO GO!";  
}

答案 1

编辑:使用或计算当天的日期。<=>=

这是您的代码的正确答案。只需使用 strtotime() php 函数。

$paymentDate = date('Y-m-d');
$paymentDate=date('Y-m-d', strtotime($paymentDate));
//echo $paymentDate; // echos today! 
$contractDateBegin = date('Y-m-d', strtotime("01/01/2001"));
$contractDateEnd = date('Y-m-d', strtotime("01/01/2012"));
    
if (($paymentDate >= $contractDateBegin) && ($paymentDate <= $contractDateEnd)){
    echo "is between";
}else{
    echo "NO GO!";  
}

答案 2

不能比较日期字符串。使用PHP的对象是一个好习惯:DateTime

$paymentDate = new DateTime(); // Today
echo $paymentDate->format('d/m/Y'); // echos today! 
$contractDateBegin = new DateTime('2001-01-01');
$contractDateEnd  = new DateTime('2015-01-01');

if (
  $paymentDate->getTimestamp() > $contractDateBegin->getTimestamp() && 
  $paymentDate->getTimestamp() < $contractDateEnd->getTimestamp()){
  echo "is between";
}else{
   echo "NO GO!";  
}

推荐