Skip to content Skip to sidebar Skip to footer

Comparing Two Dates Using Javascript Not Working As Expected

Here is my javascript code: var prevDate = new Date('1/25/2011'); // the string contains a date which // comes from a server-side script

Solution 1:

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 = newDate();
bar = newDate(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 = newDate();
bar = newDate(foo);
console.log(foo.getTime() == bar.getTime()); //prints true

Solution 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 = newDate('1/25/2011');
var currDate = newDate('1/25/2011');
console.log(prevDate == currDate ); //print false
currDate = prevDate;
console.log(prevDate == currDate ); //print truevar currDate = newDate(); //this contain current date i.e 1/25/2011
currDate.setHours(0, 0, 0, 0);
console.log(prevDate == currDate); //print falseconsole.log(prevDate.valueOf() == currDate.valueOf()); //print true

Solution 3:

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

Solution 4:

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?

Solution 5:

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

Post a Comment for "Comparing Two Dates Using Javascript Not Working As Expected"