Search code examples
javascriptreactjsangularmomentjsmoment-timezone

Moment.js - How to get weekly data [startDate & endDate of each week] for given month excluding previous and next month date


Month

For August 2020 I need data like this : - As per https://www.epochconverter.com/weeks/2020

Week 31 - 2020-08-01 to 2020-08-02

Week 32 - 2020-08-03 to 2020-08-09

Week 33 - 2020-08-10 to 2020-08-16

Week 34 - 2020-08-17 to 2020-08-23

Week 35 - 2020-08-24 to 2020-08-30

Week 35 - 2020-08-31 to 2020-08-31

As per this info

Weeks

This should work when we pass a year and month to a function as it should be generic

Required output

weekNumbers = ["Week 31", "Week 32", "Week 33", "Week 34", "Week 35", "Week 36"]; // week number should not start from 1. it should be continuos from last year.

weekList = []; // this should contain start and end date for each week

Thank you in advance


Solution

    1. Common variables used :

      const monthIndex = 8; // give month index
      const year = 2020; // give year here
      

    1. Code to get week numbers of month : -

      const getWeekNumbers = (year, month) => {
        let firstWeek = moment(new Date(year, month, 1)).isoWeek();   
        let lastWeek = moment(new Date(year, month + 1, 0)).isoWeek();
      
        let out = [`Week ${firstWeek}`];
        if (firstWeek === 52 || firstWeek === 53) {
          firstWeek = 0;
        }
      
        for (let i = firstWeek + 1; i <= lastWeek; i++) {
          out.push(`Week ${i}`);
        }
        return out;
      };
      

    1. Code for getting week list data for month : -

      function getMomentDate(start, end) {
          return {
          startDate: moment([2020, monthIndex - 1, start]),
          endDate: moment([2020, monthIndex - 1, end])
        }
      }
      
      function weeks (month) {
          const weekStartEndDay = [];
          const first = month.day() == 0 ? 6 : month.day()-1;
          let day = 7-first;
          const last = month.daysInMonth();
          const count = (last-day)/7;
      
          weekStartEndDay.push(getMomentDate(1, day));
          for (let i=0; i < count; i++) {
              weekStartEndDay.push(getMomentDate((day+1), (Math.min(day+=7, last))));
          }
          return weekStartEndDay;
      }
      

    1. Calling and getting output : -

      const month = moment([year, monthIndex - 1])
      const weekNumbers = getWeekNumbers(year, monthIndex - 1);
      const weekList = weeks(month);
      console.log("weekNumbers", weekNumbers);
      console.log("weekList", weekList);
      weekList.forEach(date => {
          console.log("start - " + date.startDate.format('YYYY-MM-DD'), "\nend - " + date.endDate.format('YYYY-MM-DD'));
      });
      

    1. Console Output for August 2020

    enter image description here

    enter image description here


    1. REPL link : - https://repl.it/@SaHiLShiKalgar/WeekNumber-and-WeekList