Why does a less than or more than comparison in PHP of two strings in the date format of “YYYY-MM-DD” work even though they are strings?

前端 未结 2 893
我寻月下人不归
我寻月下人不归 2021-01-05 00:31

I am working on a section of PHP code for a project that compares a date in the YYYY-MM-DD format to the current date to see if it is less than the current date. At differen

相关标签:
2条回答
  • 2021-01-05 01:15

    Use the DateTime class for comparing dates. It makes it a lot easier to understand, and you don't have to deal with type juggling.

    0 讨论(0)
  • 2021-01-05 01:33

    When you compare a string this way, it will go from left to right, and compare each character in the given string to see if they are different, until it finds a difference, then it will decide which string is bigger by comparing the ASCII value of this last character. Coincidentally, since you are using only numbers, the highest numbers are also higher on the ASCII table.

    This solution will work as long as you use only numbers in your comparisons, and that each string has the same number of characters

    Also note that this works only since you are using the YYYY-MM-DD format, if you used another format it would not work.

    0 讨论(0)
提交回复
热议问题