JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.
The Date object will do what you want - construct one for each date, then compare them using the >, <, <= or >=.
The ==, !=, ===, and !== operators require you to use date.getTime() as in:
var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();
to be clear just checking for equality directly with the date objects won't work.
var d1 = new Date();
var d2 = new Date(d1);
console.log(d1 == d2); // prints false (wrong!)
console.log(d1 === d2); // prints false (wrong!)
console.log(d1 != d2); // prints true (wrong!)
console.log(d1 !== d2); // prints true (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)
Here you can find more about the date.getTime() documentation
Tags:
JavaScript
It should have the explanation why this behaviour happens.
ReplyDeleteSp why is (d1 == d2) wrong?
When we are using new Date we creating new Objects. Our variables are holding the reference to this Object. So this will always be wrong. The reference cant be the same because both Objects are valid and stored somewhere in our memory.
So we have to take the real value we want to compare and this is in this case getTime()
:)