SoFunction
Updated on 2025-02-28

JS method to determine whether two dates are equal

For example:

Copy the codeThe code is as follows:

var date1 = new Date("2013-11-29");
var date2 = new Date("2013-11-29");
(date1 == date2); //false

Here, date1 and date2 look the same, but running date1 == date2 returns false. This is because date1 and date2 are both objects and their types are reference types. Therefore, if you need to compare them, you need to compare their literal values ​​instead of simply using ==.

If you want to compare whether two dates are equal, you can write this

Copy the codeThe code is as follows:

var date1 = new Date("2013-11-29");
var date2 = new Date("2013-11-29");
(() == ()); //true

Use the getTime() method to return the value corresponding to the date and then compare it.

In fact, there is another way to compare dates.

Copy the codeThe code is as follows:

var date1 = new Date("2013-11-29");
var date2 = new Date("2013-11-29");
(date1 - date2 == 0); //true

Here, subtract date2 by using date1 to get the time difference between them. If it is 0, it is definitely equal.