How to compare two dates in moment.js?

by tressie.damore , in category: Javascript , a year ago

How to compare two dates in moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , a year ago

@tressie.damore 

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:
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>


  1. Create two Moment.js objects representing the dates you want to compare:
1
2
3
// 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:
1
console.log(date1.isBefore(date2)); // Output: true


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


  • .isAfter() returns true if date1 is after date2, otherwise false:
1
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.