How to get weeks array within two dates with moment.js?

by hal.littel , in category: Javascript , a year ago

How to get weeks array within two dates with moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , a year ago

@hal.littel 

To get an array of weeks within two dates using Moment.js, you can use the following code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const moment = require('moment');

function getWeeksArray(startDate, endDate) {
  let currentWeek = moment(startDate).startOf('week');
  const endWeek = moment(endDate).endOf('week');
  const weeksArray = [];

  while (currentWeek.isSameOrBefore(endWeek)) {
    weeksArray.push({
      start: currentWeek.clone(),
      end: currentWeek.clone().endOf('week')
    });
    currentWeek.add(1, 'week');
  }

  return weeksArray;
}

const startDate = '2022-01-10';
const endDate = '2022-02-20';

const weeksArray = getWeeksArray(startDate, endDate);
console.log(weeksArray);


In this code snippet:

  1. The getWeeksArray function takes in the startDate and endDate as parameters.
  2. It initializes the currentWeek variable to the start of the week of the startDate.
  3. It creates an empty array weeksArray to store the weeks.
  4. It iterates through each week between the startDate and endDate, pushing the start and end dates of each week into the weeksArray.
  5. The function returns the weeksArray containing the weeks within the specified dates.


You can modify the startDate and endDate variables with your desired dates to get the weeks array within those dates.

Related Threads:

How to compare two dates in moment.js?
How to check if two dates are more than 7 days apart using moment.js?
How to get difference between n dates in moment.js?
How to get the data between two dates and times in laravel?
How to get days between two dates using sparql?
How to get difference between two datetime of moment.js?