Thought leadership from the most innovative tech companies, all in one place.

How to Compare Only Dates in Moment.js

How to Compare Only Dates in Moment.js

Sometimes, we want to compare only dates with moment.js

In this article, we’ll look at how to compare only dates with moment.js.

Compare Only Dates in Moment.js

We can use the isAfter method to check if one date is after another.

For instance, we can write:

const isAfter = moment("2010-10-20").isAfter("2010-01-01", "year");
console.log(isAfter);

We create a moment object with a date string.

Then we call isAfter on it with another date string and the unit to compare.

Therefore isAfter is false since we compare the year only.

There’s also the isSameOrAfter method that takes the same arguments and lets us compare if one date is the same or after a given unit.

So if we have:

const isSameOrAfter = moment("2010-10-20").isSameOrAfter("2010-01-01", "year");
console.log(isSameOrAfter);

Then isSameOrAfter is true since both dates have year 2010.

The isBefore method lets us compare is one date is before another given the unit to compare with.

So if we have:

const isBefore = moment("2010-10-20").isBefore("2010-01-01", "year");
console.log(isBefore);

Then isBefore is false since they have the same year.

isSame compares if 2 dates have the same unit.

For instance, if we have:

const isSame = moment("2010-10-20").isSame("2010-01-01", "year");
console.log(isSame);

Then isSame is true since they both have year 2010.

Conclusion

We can use the isAfter method to check if one date is after another.

Then we call isAfter on it with another date string and the unit to compare.

There’s also the isSameOrAfter method that takes the same arguments and lets us compare if one date is the same or after a given unit.

The isBefore method lets us compare is one date is before another given the unit to compare with.




Continue Learning