Performing math on date() results

The below code seems_ to work, but I don’t know if it really is valid or a strtotime() function should be called prior to doing any comparison check. Does the code actually perform a valid comparison on dates or is it just a fluke that it seems to work?

nowDay = gmdate("Y-m-d");
echo 'nowDay= ' . $nowDay . "</br>";
$nextDay = date('Y-m-d', strtotime( "2018-8-13 14:11:22"));
echo 'nextDay= ' . $nextDay . "</br>";
if($nowDay > $nextDay) echo 'greater than';
if($nowDay < $nextDay) echo 'less than';
if($nowDay == $nextDay) echo 'equal';

The answer is “yes”. Consider your format:
This, when rendered as a string (which is what the date command returns, a String.), is YYYY-MM-DD, with zero-filled months and days.
If you consider that in a String Comparison form, that goes left-to-right, character by character.
So for any two given dates, YYYY-MM-DD will always return a true comparison, because it’s evaluating the Year first, then the Month, then the Day, and because of the zerofill on Month and date, it wont get screwed up by Feburary vs November (“02” < “11” is true, because “0” < “1”.)

This only applies to zerofilled formats in the right order though, so is it valid? yes. Is it a fluke? yes, you chose a format that allows for this to happen.


Thanks @m_hutley! Awesome explanation and it makes total sense to me.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.