mongmong seesee mongmong seesee - 7 months ago 15
PHP Question

It's will be right ? for use < , > operator for compare date on php?

It's will be right ? for use

<
,
>
operator for compare date on php ?

I tested it. And it's work good. But i not founded documents for advice about use
<
,
>
operator for compare date on php.

Please tell me can we use
<
,
>
operator for compare date on php ?

<?PHP
$today = "2010-10-19";
$expired = "2012-12-10";

if($expired > $today)
{
echo "not expired";
}
else
{
echo "expired";
}
?>

Answer

As long as your dates are in a comparable format this will work. Since they are compared as strings you need to make sure that the larger dates components are first and the smaller ones last. For example, the year, then the month, then the date. Always include leading zeros. That's what you do in your example so it works.

If you do not have the dates in this format your comparison will fail some of the time. For example:

'2016-07-04' > '2016-01-07' // true
'04-07-2016' > '07-01-2016' // false

The best way to compare dates is with DateTime() as DateTime objects are comparable and also account for all things date related like leap year and DST.

<?PHP
$today = new DateTime("2010-10-19");
$expired = new DateTime("2012-12-10");

if($expired > $today)
{
    echo "not expired";
}
else
{
    echo "expired";
}