Comparing dates with strtotime

0

I have the following code:

$data = date("Y-m-d");
$dataTr = implode(preg_match("~\/~", $data_vencimento) == 0 ? "/" : "-", array_reverse(explode(preg_match("~\/~", $data_vencimento) == 0 ? "-" : "/", $data_vencimento)));

    if (strtotime($data) > strtotime($data_vencimento)):
        echo "<font color='red'>$dataTr - Vencida</font>";
    elseif(strtotime($data) == strtotime($data_vencimento)):
        echo "<font color='yellow'>$dataTr</font>";
    else:
        echo "<font color='green'>$dataTr</font>";
    endif;

It was my intention that if the $data , which would be today was greater than the due date, the date should be highlighted in red, if it were the same as today it would be yellow and if it was smaller than green, but for some reason this is not happening, and all dates are turning green, and there are dates already past. I wonder where my error is.

PS: Dates are being compared in the American AAAA / MM / DD format, according to this OS question .

    
asked by anonymous 27.03.2017 / 20:47

1 answer

1

Do not even use regular expression:

$data = date("Y-m-d"); //Data de Hoje
$dataVencimento = '2017-03-20';

if (strtotime($data) > strtotime($data_vencimento)):
    echo "<font color='red'>$dataVencimento - Vencida</font>";
elseif(strtotime($data) == strtotime($data_vencimento)):
    echo "<font color='yellow'>$dataVencimento</font>";
else:
    echo "<font color='green'>$dataVencimento</font>";
endif;

Make sure the dates are coming with the - (dash) and not / (slash) tabs. If you use / PHP will not be able to convert to timestamp , thus not letting you make the comparison.

    
27.03.2017 / 20:51