How to check if two dates are more than 7 days apart using moment.js?

Member

by denis , in category: Javascript , a year ago

How to check if two dates are more than 7 days apart using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 10 months ago

@denis 

To check if two dates are more than 7 days apart using Moment.js, you can use the diff() method to get the difference in days between the two dates, and then compare it with 7. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const moment = require('moment');

const date1 = moment('2022-01-01');
const date2 = moment('2022-01-10');

const daysApart = date2.diff(date1, 'days');

if (daysApart > 7) {
  console.log('The dates are more than 7 days apart');
} else {
  console.log('The dates are not more than 7 days apart');
}


In this example, date1 and date2 represent the two dates you want to compare. The diff() method is used to calculate the difference in days between date2 and date1. The second argument passed to diff() specifies that you want the difference in days.


Then, you can simply check if the daysApart value is greater than 7 to determine if the dates are more than 7 days apart.