The question is : How does this work anyway? How does javascript compare two strings and return true or false depending on the value in them?
When comparing two strings "2" > "14"
, "2" will be greater than "14", because (in order from left to right) that 2 is greater than 1, and likewise your "Se eu sibstituir a data por '08/05/2019', ainda recebo true"
is due as above and explained below.
General rule
To calculate string comparisons, JavaScript converts each character of a string to its ASCII value . Each character, starting with the left operator, is compared to the corresponding character in the right operator.
In the following example, see that character 7 is less than 8, so according to the general rule, regardless of what comes after character 7 of the left operator and after the character 8 of the right operator, the expression will always be false.
Note that in your case this is a comparison of two strings.
var hoje = new Date(2018, 08, 07).toLocaleDateString();
console.log(typeof hoje); //string
var dataQualquer = '08/05/2018';
console.log(typeof dataQualquer); //string
console.log(hoje); // 07/09/2018
console.log(dataQualquer); //08/05/2018
if (dataQualquer<hoje){
console.log("verdadeiro");
}else{
console.log("falso"); //8 não é menor que 7
}
See that JavaScript does not compare 7 to 8, but rather its ASCII values
7 corresponde a 055 em ASCII
8 corresponde a 056 em ASCII
NOTE: For numerical values, the results are the same as you would expect from your school algebra classes.
Easy, right? For numeric characters the ASCII values begin with 0 (048) and end with 9 (057).
Then
| cada centena representa o valor ASCII de cada caractere
07/09/2018 | 048 055 047 048 057 047 050 048 049 056
08/05/2018 | 048 056 047 048 053 047 050 048 049 056
---
For alphabetic characters is not so easy, see the example below
if ("mateus" < "Mateus"){
console.log("verdadeiro");
}else{
console.log("falso");
}
mateus | 109 097 116 101 117 115
Mateus | 077 097 116 101 117 115
---
ASCII values for uppercase letters are smaller than the corresponding lowercase letters.
One of several solutions, for your case, is to use the order MONTH DAY
var hoje = new Date(2018, 08, 07).toLocaleDateString();
var dataQualquer = '08/05/2018';
hoje = hoje.split("/").reverse().join("-"); //2018-09-07
dataQualquer = dataQualquer.split("/").reverse().join("-"); // 2018-05-08
if (dataQualquer<hoje){
console.log("verdadeiro");
}else{
console.log("falso");
}
2018-09-07 | 050 048 049 056 045 048 057 045 048 055
2018-05-08 | 050 048 049 056 045 048 053 045 048 056
---