I usually use strtotime
first to convert YYYY-MM-DD to unix timestamp then compare them but this appears to work just fine:
echo ('2015-01-01' < '2015-01-02')? 1 : 0;
// returns 1
I was wondering, is this "simpler" method reliable for basic comparison operators e.g., <
, >
, <=
, =>
?
Comparing strings in PHP using <
and >
is not a good idea because implicit type conversions to integers and other types are involved.
Using strcmp is better and will actually work, dates in YYYY-mm-dd have the same ordering chronologically and alphabetically. It is often used in databases where an index is created on a datetime column and then using WHEREs the column is filtered by comparing strings.
I will strongly recommend though creating \DateTime
or \DateTimeImmutable
objects and working with those (you can use comparison operators on them). UNIX timestamps were a good choice before PHP 5.2, but today the object approach is the better one.