简体   繁体   中英

Why Date comparison is showing weird behavior in javascript?

When I'm working with date comparison in javascript, in the browser console I did perform the following operations.

new Date() >= new Date() returned true

new Date() <= new Date() returned true

this looked good as I thought both are equal, if I was correct then

new Date() == new Date() should returns true

Interestingly it returned false . Then I performed below operations as well

new Date() > new Date() returned false

new Date() < new Date() returned false

new Date() != new Date() returns true

which was also fine with my assumption.

If both the new Date() s were returning same time then == should return true along with the >= and <= , other wise either of > or < should return ture as != returning true .

Following table consists expected results and actual results for different cases.

在此输入图像描述

Why is the ACTUAL results column not following any of its preceding columns?

Use Date.getTime to compare the timestamp, otherwise you are simply comparing the objects, which we know aren't the same.

 var d1 = new Date(), d2 = new Date(); function fullCompare(a, b) { console.log(a == b, a <= b, a >= b, a < b, a > b); } fullCompare(d1, d2); fullCompare(d1.getTime(), d2.getTime()); 

Check for equality like you're doing compares the references to the objects. To compare the actual values of the objects themselves, the most common practice is to call getTime() method, which will return the number of milliseconds since 1970-01-01 00:00:00 UTC.

Therefore, the following code will return true :

(new Date()).getTime() == (new Date()).getTime()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM