Categories
JavaScript Answers

How to Compare the Date Part of a Date Object Only Without Comparing the Time in JavaScript?

Spread the love

Sometimes, we may want to compare the date part of a date only without comparing the time in our JavaScript app.

In this article, we’ll look at how to compare the date without comparing the time with JavaScript.

Date.prototype.setHours

To compare dates without comparing the time portion, we can set both dates to midnight by using the setHours method that comes with JavaScript date objects.

For instance, we can write:

const date1 = new Date(2021, 1, 1, 1, 1, 1)
date1.setHours(0, 0, 0, 0)

const date2 = new Date(2021, 2, 1)
date2.setHours(0, 0, 0, 0)

console.log(+date2 > +date1)

We call setHours on date1 to set the hours, minutes, and seconds of date1 all to 0.

This will set the date to midnight.

Then we can compare them both without the time part with the > operator as we did in the last line,

To be safe, we convert them both to timestamps first with the + operator.

Therefore, the console log should show true since date2 is ahead of date1 .

To be even safer, we can do both date comparisons after converting them both to UTC date-times.

To do this, we write:

const date1 = new Date(2021, 1, 1, 1, 1, 1)
const date1Copy = new Date(Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate()));
date1Copy.setHours(0, 0, 0, 0)

const date2 = new Date(2021, 2, 1)
const date2Copy = new Date(Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate()));
date2Copy.setHours(0, 0, 0, 0)

console.log(+date2Copy > +date1Copy)

We call Date.UTC with the date parts retrieved from date1 and date2 to create a UTC timestamp.

Then we pass them into the Date constructor to create new date objects.

Then we call setHours on the copied dates and then do the comparison with them.

And we should get the same result from the console log.

Moment.js

The moment.js library has the isAfter method that lets us compare 2 date-times without the time part.

To do this, we write:

const date1 = new Date(2021, 9, 20, 12, 0, 0);
const date2 = new Date(2021, 9, 20, 12, 1, 0);
const isAfter = moment(date2).isAfter(date1, 'day');

console.log(isAfter)

We call isAfter on the moment date object created with the date2 date object.

And we pass in 'day' into the 2nd argument to exclude the time part of each date from the comparison.

Therefore, isAfter should be false as a result since they’re both the same date excluding the time part.

Conclusion

We can use native JavaScript date methods or moment.js to compare dates without the time part.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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