0

I tried comparing 2 same dates in the chrome console:

new Date("2021-06-23") == new Date("2021-06-23")

It is giving false

new Date("2021-06-23") > new Date("2021-06-23")

It is giving false

But, new Date("2021-06-23") >= new Date("2021-06-23")

It is giving true

I couldn't understand why it is giving true for greater than or equal to but false for both greater than also and for equals to as well.

Please explain.

7
  • 1
    == when applied to objects checks if they are the same object, not if two different objects but with similar content. Relationship operators instead do implicit conversion. Commented Jul 27, 2021 at 18:36
  • 1
    ^ This. By contrast, Date objects have defined behaviour for >/>=/</<= operators that compares the date value. Commented Jul 27, 2021 at 18:36
  • I should also point out that since you aren't defining the time portion of the date, there's no guarantee that new Date("2021-06-23") == new Date("2021-06-23") would be true anyway, as the millisecond may change between calls. Commented Jul 27, 2021 at 18:37
  • 2
    Does this answer your question? JavaScript Date Object Comparison. Also see JavaScript Date Comparisons Don't Equal. Commented Jul 27, 2021 at 18:37
  • 1
    @NiettheDarkAbsol if a ISO date string is passed then the milliseconds will be initialised to zero. Commented Jul 27, 2021 at 18:42

2 Answers 2

0

Because new Date create an unique object.

Even if they have the sames properties, 2 distinct objects will never been equals.

const x = {a : "aaa"};
const y = {a : "aaa"};

console.log(x == y); // false

const z = x; // litteraly the same object

console.log(x == z); // true

Sign up to request clarification or add additional context in comments.

Comments

0

The Date object don't support grater or equal operators per se... It has something like Symbol.toPrimitive

It's a function that gets called when it should be converted to the appropriated primitive value

const object1 = {
  [Symbol.toPrimitive](hint) {
    if (hint === 'number') {
      return 42;
    }
    return null;
  }
};

console.log(+object1);
// expected output: 42

So if you want to compare if two dates are equals then you can do

+new Date() === +new Date()

when you use any of this operators + - * / < > then it wishes to convert it to a number so you are actually comparing numbers and not objects

1 Comment

A better reference is ECMA-262 Abstract Relational Comparison Algorithm, which uses the plain ToPrimitive abstract operation. Symbol.ToPrimitive is specifically for Symbol objects, not Date objects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.