7

Here is my javascript code:

var prevDate = new Date('1/25/2011'); // the string contains a date which
                                      // comes from a server-side script
                                      // may/may not be the same as current date

var currDate = new Date();            // this variable contains current date
    currDate.setHours(0, 0, 0, 0);    // the time portion is zeroed-out

console.log(prevDate);                // Tue Jan 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
console.log(currDate);                // Tue Jan 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
console.log(prevDate == currDate);    // false -- why oh why

Notice that both dates are the same but comparing using == indicates they are not the same. Why?

Salman A
  • 262,204
  • 82
  • 430
  • 521

5 Answers5

13

I don't think you can use == to compare dates in JavaScript. This is because they are two different objects, so they are not "object-equal". JavaScript lets you compare strings and numbers using ==, but all other types are compared as objects.

That is:

var foo = "asdf";
var bar = "asdf";
console.log(foo == bar); //prints true

foo = new Date();
bar = new Date(foo);
console.log(foo == bar); //prints false

foo = bar;
console.log(foo == bar); //prints true

However, you can use the getTime method to get comparable numeric values:

foo = new Date();
bar = new Date(foo);
console.log(foo.getTime() == bar.getTime()); //prints true
nss
  • 541
  • 3
  • 9
2

Dont use == operator to compare object directly because == will return true only if both compared variable is point to the same object, use object valueOf() function first to get object value then compare them i.e

var prevDate = new Date('1/25/2011');
var currDate = new Date('1/25/2011');
console.log(prevDate == currDate ); //print false
currDate = prevDate;
console.log(prevDate == currDate ); //print true
var currDate = new Date(); //this contain current date i.e 1/25/2011
currDate.setHours(0, 0, 0, 0);
console.log(prevDate == currDate); //print false
console.log(prevDate.valueOf() == currDate.valueOf()); //print true
Gajahlemu
  • 1,253
  • 7
  • 17
1

Try comparing them using the date method valueOf(). This will compare their primitive value underneath instead of comparing the date objects themselves.

Example: console.log(prevDate.valueOf() == currDate.valueOf()); //Should be true

nybbler
  • 4,793
  • 28
  • 23
1
console.log(prevDate.getTime() === currDate.getTime());

(as nss correctly pointed out, I see now) Why I use === here? have a look Which equals operator (== vs ===) should be used in JavaScript comparisons?

Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

JS compares dates using the > and < operators. If a comparison returns false, they're equal.

Julio Santos
  • 3,837
  • 2
  • 26
  • 47