Home > Software engineering >  How to get list of months between 2 years in typescript for angular
How to get list of months between 2 years in typescript for angular

Time:02-17

I have a fromDate and toDate coming from a datepicker - Assuming the fromDate is 05-Sep-2021 and toDate is 02-Feb-2022, I need the list of the missing months between the two. I initially tried with the moment.js and using arr.reduce and arr.findIndex functions. But not getting the expected output. Kindly help.

Eg.

var arr = [
  {month: 7,  year: 2021, count: 21},
  {month: 12, year: 2021, count: 54},
  {month: 2,  year: 2022, count: 76}
];

Expected o/p =

[
  {month: 7,  year: 2021, count: 21}, 
  {month: 8,  year: 2021, count: 0},
  {month: 9,  year: 2021, count: 0},
  {month: 10, year: 2021, count: 0},
  {month: 11, year: 2021, count: 0},
  {month: 12, year: 2021, count: 54},
  {month: 1,  year: 2022, count: 0},
  {month: 2,  year: 2022, count: 76}
];

CodePudding user response:

One way to do this is to think of the Year & Month as one value. eg. var ym = year * 12 (month - 1)

If you do this then you can compare the YM value to the next item in the array, if it's below then you can insert a new item into the array between them.

Update, added two utility function to make this easier, YM, will basically convert Year/Month into a linear number, and then RYM will convert this number back into {year, month}, Bonus, I think it makes the code slightly easier to follow too.

Below is an example..

var arr = [
  {month: 7,  year: 2021, count: 21},
  {month: 12, year: 2021, count: 54},
  {month: 2,  year: 2022, count: 76}
];

/*var arr = [
  {month: 11, year: 2021, count: 54}, 
  {month: 2, year: 2022, count: 76} 
]; */

const YM = ({year, month}) => year * 12   month - 1;

const RYM = ym => ({
   year: Math.trunc(ym / 12), 
   month: (ym % 12)   1
});


function fillSpace(arr) {
  let st = 0;
  while (st < arr.length -1){
    const thisYM = YM(arr[st]);
    const nextYM = YM(arr[st   1]);
    if (thisYM   1 < nextYM) 
      arr.splice(st   1, 0, {
        ...RYM(thisYM   1),
        count: 0
      });     
    st  = 1;
  }
}

fillSpace(arr);

console.log(arr);

CodePudding user response:

new Date(new Date(d2) - new Date(d1)).getMonth();

  • Related