Comparing Dates In Javascript Without The Time Component

I came across an interesting problem recently where I had to check if a date was before or after today. Getting todays date seemed trivial :

let today = new Date();

But in my test cases, things were blowing up, often at weird times of the day. And it occurred to me that I wasn’t just comparing dates, I was comparing the times on those date objects too!

Such is Javascript, there isn’t actually a way to ask a date object for *only* the date portion for comparisons sake, it always has a time component attached. So for example if I have something like so :

let someDate = someService.getTheDate();// Returns Sat Jan 16 2021 08:30:00
let today = new Date();// Returns Sat Jan 16 2021 9:30:00
let isSameDay = today == someDate; // False!

It’s comparing the time as well as the date!

A very very common pitfall is assuming that the method .getDate() on a Date object will return the date.. Well.. It does, but only the day of the month. So in our example, it will return 16 as in the 16th of Jan. But obviously if you are comparing dates across different months, this isn’t going to work!

So how can we compare just the dates? There is some.. shall we say… interesting fixes out there. One that seems the most prominent is to zero out the time portion :

let today = new Date();// Returns Sat Jan 16 2021 9:30:00
today.setHours(0, 0, 0, 0); // Today is now Sat Jan 16 2021 0:00:00

But the issue with this method is that your date object now has a zero’d out time so if you want to use it elsewhere, you should first clone the date object, then zero it out, then compare it. Something like so :

let today = new Date();// Returns Sat Jan 16 2021 9:30:00
let clonedDate = new Date(today);
clonedDate.setHours(0, 0, 0, 0); // Today is now Sat Jan 16 2021 0:00:00
console.log(today);// Still returns Sat Jan 16 2021 9:30:00

However, this setHours method didn’t sit well with me. It was somewhat ambiguous what it was doing, even with the cloning. So my prefered approach was actually to create a new date object using only the parts I cared about.

let today = new Date();// Returns Sat Jan 16 2021 9:30:00
let clonedDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());

Then I can compare clonedDate to another date that we create using only the date portion, and the comparison works perfect!

Leave a Reply

Your email address will not be published. Required fields are marked *