Need to understand how date works when comparing multiple dates
console.log(new Date('2019-10-10T05:00:00.000+0000') >= new Date('2019-10-10T10:30:00.000+0530')) // true
console.log(new Date('2019-10-10T05:00:00.000+0000') <= new Date('2019-10-10T10:30:00.000+0530')) // true
console.log(new Date('2019-10-10T05:00:00.000+0000') == new Date('2019-10-10T10:30:00.000+0530')) // false
console.log(+new Date('2019-10-10T05:00:00.000+0000') == +new Date('2019-10-10T10:30:00.000+0530')) // true
How come the first two statements returns true and third false. Requesting an explanation/links, please.
In the third comparison:
console.log(new Date('2019-10-10T05:00:00.000+0000') == new Date('2019-10-10T10:30:00.000+0530')) // false
you are just comparing two objects which are not the very same object, hence returns false. MDN explains:
Two distinct objects are never equal for either strict or abstract comparisons.
The fourth comparison:
console.log(+new Date('2019-10-10T05:00:00.000+0000') == +new Date('2019-10-10T10:30:00.000+0530')) // true
forces the conversion to numbers though by using the +
sign.
And for the first and second comparisons:
console.log(new Date('2019-10-10T05:00:00.000+0000') >= new Date('2019-10-10T10:30:00.000+0530')) // true
console.log(new Date('2019-10-10T05:00:00.000+0000') <= new Date('2019-10-10T10:30:00.000+0530')) // true
MDN explains the behavior of <
<=
>
>=
relational operators:
Each of these operators will call the valueOf() function on each operand before a comparison is made.
so it calls valueOf()
function on date
objects returning timestamps
which are numbers, thus evaluating to true
.