Home > Enterprise >  PHP - Is a date in the past
PHP - Is a date in the past

Time:10-27

I'm trying to compare if a date is today, or in the past. As far as i can tell i should be able to do date1 <= today but it shows as true even if the date is in the future

I'm getting the date from the database and adding 30 days to it using

echo "End Date: " . $rowTicket['endDate'] . "<br/>";
$disableDate = ($rowTicket['endDate'] != '0000-00-00') ? date('d-m-Y', strtotime(' 30 days', strtotime($rowTicket['endDate']))) : '';

And then doing the check using

echo "Is " . $disableDate . " before today's date? (" . date("d-m-Y") . ")";
if($disableDate <= date("d-m-Y")) {
    //$colourTR = $red;
    echo " - Yes<br/><br/>";
} else {
    echo " - No<br/><br/>";
}

The output i get from the echo's is

End Date: 2021-09-01

Is 01-10-2021 before today's date? (26-10-2021) - Yes

End Date: 2021-10-15

Is 14-11-2021 before today's date? (26-10-2021) - Yes

CodePudding user response:

Because you compare strings, while should compare timestamps


echo "End Date: " . $rowTicket['endDate'] . "<br/>";
$disableDate = $rowTicket['endDate'] != '0000-00-00'
    ? strtotime(' 30 days', strtotime($rowTicket['endDate']))
    : '';

$today = strtotime('today midnight');
echo "Is {$disableDate} before today's date? (" . date("d-m-Y", $today) . ")";

if($disableDate <= $today) {
    //$colourTR = $red;
    echo " - Yes<br/><br/>";
} else {
    echo " - No<br/><br/>";
}

CodePudding user response:

You are formatting your dates as strings. PHP has no way of knowing that the string '26-10-2021' should be "less than" the string '14-11-2021'.

If you format them year-first ('Y-m-d'), it will work, but better to compare the integer timestamps (output of strtotime), or DateTimeImmutable objects.

  • Related