Last Updated: February 25, 2016
·
1.429K
· idl3

Comparing Javascript Date Objects

Previously shared by my good friend link
I wondered how do you effectively compare Javascript Dates modularly and concisely.

Basically if you would try to compare a javascript Date Object you would probably never get an equal statement firing true. That is because they are comparing the objects and not comparing the actual datetime info it contains.

My approach to comparison of dates would be to first.

Get them both to tangible values we can work with.
We do this with the valueOf method or the getTime method, I will use valueOf for this example :)

var a = new Date();
var b = new Date();
var c = new Date();
c.setHour(c.getHour() + 1); // set to 1 hour after var a & b

a == b; // returns false
a > b; // returns false
a < b; // returns false

b.valueOf() == a.valueOf(); // returns true
c.valueOf() > a.valueOf(); // returns true

parseInt(b.valueOf() / 1000) == parseInt(a.valueOf() / 1000); // comparing he values removing milliseconds. Should still return true.

parseInt(c.valueOf() / 1000/60/60/24) == parseInt(a.valueOf() / 1000/60/60/24); // comparing C to B but this time ignoring hour difference. only comparing day itself. Should return true.

Take note that after this you will not be able to account for monthly differences due to the calendar month differences.