How to compare moment.js date?

by haylee.mertz , in category: Javascript , 6 months ago

How to compare moment.js date?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 6 months ago

@haylee.mertz 

To compare moment.js dates, you can use moment.js's .isBefore(), .isSame(), and .isAfter() methods. These methods take another moment.js object or a string in a recognized date/time format as a parameter and return a boolean value indicating whether the current moment.js object is before, same as, or after the provided date.


Here's an example of how you can compare moment.js dates:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// Import moment.js library if you haven't already
const moment = require('moment');

// Create two moment.js dates
const date1 = moment('2022-03-15', 'YYYY-MM-DD');
const date2 = moment('2022-03-20', 'YYYY-MM-DD');

// Compare the dates
console.log(date1.isBefore(date2)); // true
console.log(date1.isSame(date2)); // false
console.log(date1.isAfter(date2)); // false

// You can also compare using strings directly
console.log(date1.isBefore('2022-03-20')); // true
console.log(date1.isSame('2022-03-15')); // true
console.log(date1.isAfter('2022-03-10')); // true


In the example above, isBefore() returns true because date1 is before date2. isSame() returns false because the dates are not the same. isAfter() also returns false because date1 is not after date2. Finally, by comparing the dates with strings directly, we get the same result.