Comparing two dates using JavaScript not working as expected [duplicate]

放肆的年华 提交于 2019-12-10 22:56:02

问题


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?


回答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 = 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



回答2:


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




回答3:


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?




回答4:


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



回答5:


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



来源:https://stackoverflow.com/questions/4790828/comparing-two-dates-using-javascript-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!