Reputation: 415
I just found this code to be working just fine (Chrome, Firefox, Node.js):
"2018-06-02" > "2018-05-10"
<- true
"2018-06-02" > "2020-05-10"
<- false
Is this really intended to work like this? I can't find anything about comparing such formatted strings in JavaScript apart from converting them into individual Date objects and comparing them afterwards. What is happening here, are the strings converted into numbers/dates/chars internally?
This incorrect statement seems to work as well in some way:
"2018-06-20" > "2018-05-40"
<- true
Upvotes: 0
Views: 53
Reputation: 1074118
Is this really intended to work like this?
If the strings are valid dates, it's fine, but not specifically because they're dates.
Strings are compared in lexicographic (loosely, alphabetic) order, left to right. Since "0" is less than "1", and "1" is less than "2", etc., and since those strings have the most significant date portion (years) first and the least significant portion (days) last, lexicographic order also happens to be date order.
If the strings were in the European DD/MM/YYYY format, or the U.S. MM/DD/YYYY format, it wouldn't work, because those don't have the most date parts in order most significant to least significant.
The reason "2018-06-20" > "2018-05-40"
is true but comparing them as dates, using a reasonable interpretation of what that second one should mean (the date 2018-06-09), would be false is that, again, they're compared as strings, character by character. No normalization is done, no date-specific logic at all.
Upvotes: 2
Reputation: 138257
You can compare any kind of string.
"a" < "b"
This is called lexicographic comparison. It will go from left to right, char by char, and will compare the position in the alphabet if the character is different. For number digits with the same length that will work as expected, so it will also work for ISO date strings.
Some examples where it does not work:
"19" > "2" // false, "2" is bigger "1"
"12:35 23.4.2019" < "12:34 25.4.2019" // false, "4" is smaller "5"
Upvotes: 0