如何获取基于月份的dateRange

时间:2020-01-26 02:52:54

标签: javascript arrays reactjs typescript javascript-objects

我正在尝试根据该月的周初到周末在一个月内获取dateRange。因此,例如,如果我经过了2020年1月,则dateRange应该从[2019-12-30到2020-01-31]中获取数据,

2月= [2020-02-03至2020-02-28],
3月= [2020-03-02至2020-04-03]

enter image description here

2 个答案:

答案 0 :(得分:3)

我建议您检查一下moment.js(https://momentjs.com/docs/#/get-set/week/

希望这会有所帮助:)

答案 1 :(得分:0)

感谢@ Kaca992这就是我为我工作的东西,它仍然可以重构。 #MakeThisCodeBetter

   function GregorianWeeksInAYear(){

        let year = 2020;
        let month = 0;
        let startDate = "";
        let endDate = "";

         const monthsInYear = [];


      while (month < 12){
       let isLeapYear = moment([year]).isLeapYear();

     if(isLeapYear){
     if(month > 0){
       startDate = moment([year,month]).startOf('month').isoWeekday(1).add(7,'days');

     }
      else{
         startDate = moment([year,month]).startOf('month').isoWeekday(1);

      }

       endDate = 


moment([year,month]).endOf('month').isoWeekday(1).add(5,'days').subtract(1,'days');
     }
       else{
     startDate = moment([year,month]).startOf('month').isoWeekday(1);

    endDate = moment([year,month]).endOf('month').isoWeekday(1).add(4,'days');
    }
       monthsInYear.push({start:moment(startDate).format('YYYY-MM-DD'),end:moment(endDate).format('YYYY-MM-DD'),name: moment(startDate).add(4,'days').format('MMMM')})

   month++;
        }

     return monthsInYear;
          }