Compare two dates in JavaScript using moment.js

Moment.js is a great JavaScript library to work with date and time. If you’re looking for a solution to compare two dates in JavaScript, look no further than moment.js. It’s got great stock functions to help you play with date and time.

Get current time

To get the current time in moment.js you just call moment(). All moment calls use lowercase moment.

var current = moment();
console.log(current.toString());
// Tue Nov 12 2019 21:44:19 GMT+0530

Check if two dates are same

To compare two dates, just convert the dates to moment object and use the isSame() function.

moment('2019-11-11').isSame('2019-11-11'); // true

Compare if only day is the same.

moment('2019-05-11').isSame('2019-05-11','day'); // true
moment('2019-05-11').isSame('2019-05-12','day'); // false

Check if months are equal.

moment('2019-05-11').isSame('2019-05-12','month'); // true
moment('2019-05-11').isSame('2019-06-12','month'); // false

Check for year.

moment('2019-05-11').isSame('2019-05-12','year'); // true
moment('2018-05-11').isSame('2019-06-12','year'); // false

Check if a date is after another date

moment('2019-05-12').isAfter('2019-05-11'); //true
moment('2019-05-11').isAfter('2019-05-12'); //false

Check if a date is after another date

moment('2019-05-12').isBefore('2019-05-11'); //false
moment('2019-05-11').isBefore('2019-05-12'); //true