JavaScript 日期对象比较

当比较 Javascript 中的日期对象时,我发现即使比较相同的日期也不会返回 true。

 var startDate1 = new Date("02/10/2012");
var startDate2 = new Date("01/10/2012");
var startDate3 = new Date("01/10/2012");
alert(startDate1>startDate2); // true
alert(startDate2==startDate3); //false

我如何比较这些日期的相等性?我对使用 JS 的原生 Date对象而不是任何第三方库感兴趣,因为仅仅使用第三方 JS 来比较日期是不合适的。

90339 次浏览

That is because in the second case, the actual date objects are compared, and two objects are never equal to each other. Coerce them to number:

 alert( +startDate2 == +startDate3 ); // true

If you want a more explicity conversion to number, use either:

 alert( startDate2.getTime() == startDate3.getTime() ); // true

or

 alert( Number(startDate2) == Number(startDate3) ); // true

Oh, a reference to the spec: §11.9.3 The Abstract Equality Comparison Algorithm which basically says when comparing objects, obj1 == obj2 is true only if they refer to the same object, otherwise the result is false.

Compare dates using getTime() returning number of milliseconds from epoch (i.e. a number):

var startDate1 = new Date("02/10/2012");
var startDate2 = new Date("01/10/2012");
var startDate3 = new Date("01/10/2012");
alert(startDate1.getTime() > startDate2.getTime()); // true
alert(startDate2.getTime() == startDate3.getTime()); //true

Also consider using Date constructor taking explicit year/month/date number rather then relying on string representation (see: Date.parse()). And remember that dates in JavaScript are always represented using client (browser) timezone.

you can compare the actual milliseconds :

alert(startDate2.getTime() === startDate3.getTime());

You do not need to use the getTime method- you can subtract a date object from another date object. It will return the milliseconds difference(negative, if the second is a later date)

var startDate1 = new Date("02/10/2012");
var startDate2 = new Date("01/10/2012");


var diff= (startDate1 -startDate2)

// evaluates to 0 if the dates have the same timestamp

You can also use the function valueOf()

 var startDate1 = new Date("02/10/2012").valueOf();
var startDate2 = new Date("01/10/2012").valueOf();
var startDate3 = new Date("01/10/2012").valueOf();
alert(startDate1>startDate2); // 1326150000000 > 1328828400000   true
alert(startDate2==startDate3); // 1328828400000 > 1326150000000  false

tl;dr

Use date.getTime() for comparisons.
Based on my testing, it was at least 25% than the next fastest alternative (date.valueOf()).

Details

Came across this in 2022. As others have already said, comparing like date1.getTime() === date2.getTime() is the way to go.

Someone else shared a jsperf link in an answer that seems broken for me right now, so decided to add some performance comparison of my own.

I created two arrays containing 1000 dates each. All dates will naturally be different instances (meaning direct === checks will fail), so what this benchmark does, is test what the fastest way is to convert a date to a primitive.

Here's the test data:

const data1 = Array.from({length: 1000}, () => new Date())
const data2 = Array.from({length: 1000}, () => new Date())

And here are the test cases (there's more in the link below):

// 1
data1.forEach((d1, i) => d1.getTime() === data2[i].getTime());


// 2
data1.forEach((d1, i) => d1.valueOf() === data2[i].valueOf());


// 3
data1.forEach((d1, i) => Number(d1) === Number(data2[i]));


// 4
data1.forEach((d1, i) => d1.toISOString() === data2[i].toISOString());

Result (use date.getTime())

Not a surprise that a date.getTime() conversion is much faster. It's around 25% faster than date.valueOf(), and between 10x and 100x faster than everything else (as far as I've checked).

Additionally, introducing optional chaining slowed the best case by almost 10% for me. Found that interesting. date.valueOf() also slowed down by 5% compared to its non optional chaining counterpart.

data1.forEach((d1, i) => d1?.getTime() === data2[i]?.getTime());

Benchmark link: here

Here's an image, in case the above link breaks at some point in the future.

benchmark image

One more way of comparing two dates would be converting dates to timestamps using "+" operator before the date.

So, let's say we have two dates:

const dateOne = new Date("10 January 1986")
const dateTwo = new Date("10 December 2020")
if(+dateOne == +dateTwo){
//do something
}

and so on. This is really handy if you are sorting date objects too as you can use this in the sorting callback function.