How to compare two dates in moment.js?

by tressie.damore , in category: Javascript , 7 months ago

How to compare two dates in moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 5 months ago


In Moment.js, you can compare two dates using the .isBefore(), .isSame(), or .isAfter() methods. Here's how you can use them:

  1. Install Moment.js if you haven't already by adding this to your HTML file:
<script src=""></script>

  1. Create two Moment.js objects representing the dates you want to compare:
// Create Moment.js objects with your dates
var date1 = moment('2022-01-01', 'YYYY-MM-DD');
var date2 = moment('2022-02-01', 'YYYY-MM-DD');

  1. Compare the dates using the desired method:
  • .isBefore() returns true if date1 is before date2, otherwise false:
console.log(date1.isBefore(date2)); // Output: true

  • .isSame() returns true if date1 is the same as date2, otherwise false:
console.log(date1.isSame(date2)); // Output: false

  • .isAfter() returns true if date1 is after date2, otherwise false:
console.log(date1.isAfter(date2)); // Output: false

You can also pass an optional second argument to these methods to specify the unit you want to compare. For example, .isBefore(date, 'month') will check if date1 is before date2 in terms of month.