William William - 2 years ago 99
PHP Question

My date check statement isn't working properly

I have a date checker that checks if a date is between 2 other dates, but it's not working properly.

$maxDate = date('d/m/Y');
$minDate = date('d/m/Y', strtotime("-30 days"));
$date = $unit['date_recorded'];


string(19) "2016-05-02 15:27:15"

Now I have the statement:

if ($date >= $minDate AND $date <= $maxDate) { // do something }

But it never triggers this statment, even if I try to transform the
date("d/m/Y", $date)
or use
or all variables.

What am I doing wrong?

Answer Source

Problem #1

Both dates must have the same format for the comparison to work.

Problem #2

If I try to transform the $date with date("d/m/Y", $date)

The reason why it's not working is because the date function accepts a time, not a string.

To make it work, you have to do

date("d/m/Y", strtotime($date))

However, this was just a side problem. The reason why you cannot compare dates with the d/m/Y is because:

$minDate = date('d/m/Y', strtotime("-30 days")); // 30/04/2016
$maxDate = date('d/m/Y'); // 30/05/2016
$date = date('d/m/Y', strtotime($unit['date_recorded'])); // 02/05/2016

As you can see, $date starts with 02 which is less than the $minDate's 30. It's taking the day in consideration before the year, or the month. So it's never going inside your if-case.

Solution #1 - Convert all dates to Y-m-d format

Declare the value of $unit['date_recorded'] for testing purposes:

$unit['date_recorded'] = "2016-05-02 15:27:15";

Now that we have a value for the unit variable, here's how we proceed:

$minDate = date('Y-m-d', strtotime("-30 days"));
$maxDate = date('Y-m-d');
$date = $unit['date_recorded'];

if($date >= $minDate && $date <= $maxDate)
    echo "Do something...";

Solution #2 - Convert all dates to unix timestamp

$minDate = strtotime("-30 days");
$maxDate = time();
$date = strtotime($unit['date_recorded']);

if($date >= $minDate && $date <= $maxDate)
    echo "Do something...";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download