-2
var d1 = new Date("02/22/2018");
var d2 = new Date("02/22/2018");
if(d1 == d2){

}

** - this is not working. its always return false. but if I write a condition as bellow then its working fine.**

if(d1 <= d2 && d1 >= d2){

       }
Viru
  • 1
  • 1
  • 8
  • 2
    You're comparing two different object refrences, they are never the same. Use `var d1 = new Date("02/22/2018").getTime()` to get comparable values to the date variables. – Teemu Feb 26 '18 at 07:53
  • But d1 <= d2 working fine. Then why I need to write .gettime() for checking == – Viru Feb 26 '18 at 08:04

4 Answers4

0

Dates are objects, and are compared by reference, bot by value. Try this:

d1.getTime() === d2.getTime();
Zlatko
  • 18,936
  • 14
  • 70
  • 123
0

It might be checking the reference. Can you try

var d1 = new Date("02/22/2018");
var d2 = new Date("02/22/2018");
if(d1.getTime() === d2.getTime()){

}
Arun Ghosh
  • 7,634
  • 1
  • 26
  • 38
0

You can use .getTime(); method to compare two date objects.

var d1 = new Date("02/22/2018");
var d2 = new Date("02/22/2018");

console.log(d1.getTime() == d2.getTime())

console.log(d1.valueOf() == d2.valueOf())

The getTime() method returns the date as an integer, what you are doing there is comparing objects, rather than value.

Instead of getTime() you can also use valueOf(). The valueOf() method returns the primitive value of the specified object

Arun CM
  • 3,345
  • 2
  • 29
  • 35
0

You can do this way.

var d1 = new Date("02/22/2018");
var d2 = new Date("02/22/2018");
if (d1.getTime() === d2.getTime()) {
    console.log("same");
} else {
    console.log("differ");
}
Chintan Joshi
  • 1,207
  • 1
  • 9
  • 17