[removed] get all months between two dates?

后端 未结 10 627
醉酒成梦
醉酒成梦 2020-12-09 10:12

I have two date strings like this:

var startDate = \'2012-04-01\';
var endDate = \'2014-11-01\';

And I want to end up with an array of stri

10条回答
  •  一向
    一向 (楼主)
    2020-12-09 10:25

      const getMonths = (fromDate, toDate) => {
        const fromYear = fromDate.getFullYear();
        const fromMonth = fromDate.getMonth();
        const toYear = toDate.getFullYear();
        const toMonth = toDate.getMonth();
        const months = [];
        for(let year = fromYear; year <= toYear; year++) {
          let month = year === fromYear ? fromMonth : 0;
          const monthLimit = year === toYear ? toMonth : 11;
          for(; month <= monthLimit; month++) {
            months.push({ year, month })
          }
        }
        return months;
      }
    const sample = getMonths(new Date('2022-07-28'), new Date('2023-03-20'));
    console.log(sample);
    document.write('check the console output');

    https://jsfiddle.net/xfayoqvs/

提交回复
热议问题