Comparison of dates with strtotime

Asked

Viewed 253 times

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;

My intention was that I should marry $data, that today would be longer than the due date, the date should be highlighted in red, if it was equal to today it would be in yellow and if it was smaller it would be in green, but for some reason this is not happening, and all dates are turning green, and there are expired dates. I wonder where my mistake lies.

P.S: The dates are being compared in American format YYYY/MM/DD, according to data from this question of the OS.

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 tab - (dash) and not / (bar). If you use / PHP will not be able to convert to timestamp, thus not letting you make the comparison.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.