DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Originally published at thewebdev.info

How to Compare Two Dates with JavaScript?

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

Comparing 2 dates is something we’ve to do often in a JavaScript app.

In this article, we’ll look at how to compare 2 dates with JavaScript.

Comparing Timestamps

One easy way to compare 2 dates is to compare their timestamps.

We can get the timestamp with the getTime method.

For instance, we can write:

const d1 = new Date();  
const d2 = new Date(d1);  
const same = d1.getTime() === d2.getTime();  
const notSame = d1.getTime() !== d2.getTime();
Enter fullscreen mode Exit fullscreen mode

getTime returns the UNIX epoch in seconds.

It’s time number of seconds since January 1, 1970 midnight UTC.

We can also write:

const d1 = new Date();  
const d2 = new Date(d1);  
const same = +d1 === +d2;  
const notSame = +d1 !== +d2;
Enter fullscreen mode Exit fullscreen mode

which replaces getTime with the + before the date objects.

It does the same thing as getTime .

Relational Operators

We can use relational operators directly with date objects.

For instance, we can write:

const d1 = new Date(2021, 0, 1);  
const d2 = new Date(2021, 0, 2);  
d1 < d2;  
d1 <= d2;  
d1 > d2;  
d1 >= d2;
Enter fullscreen mode Exit fullscreen mode

to compare them directly with the relational operators.

d1 and d2 will be converted to timestamps before comparing.

Subtracting Dates

We can also subtract one date from another and compare the result to what we want.

For instance, we can write:

const d1 = new Date(2021, 0, 1);  
const d2 = new Date(2021, 0, 2);  
console.log(d1 - d2 === 0);  
console.log(d1 - d2 < 0);  
console.log(d1 - d2 > 0);
Enter fullscreen mode Exit fullscreen mode

This works because d1 and d2 are converted to timestamps before we subtract them.

Comparing Year, Month, and Date

We can compare the year, month, and day of 2 date objects to check if they’re the same to determine if they’re the same date.

For instance, we can write:

const d1 = new Date(2021, 0, 1);  
const d2 = new Date(2021, 0, 2);  
const isSameDate = d1.getFullYear() === d2.getFullYear() &&  
  d1.getDate() === d2.getDate() &&  
  d1.getMonth() === d2.getMonth();
Enter fullscreen mode Exit fullscreen mode

getFullYear returns the 4 digit year number.

getDate returns the date.

And getMonth returns the month from 0 to 11. 0 is January, 1 is February, etc.

Conclusion

We can compare 2 dates easily with JavaScript by converting them to numbers with various operators.

Then we can compare them.

We can also compare their year, month, and day values individually.

Top comments (0)