Home > database >  Display months between two dates with different years
Display months between two dates with different years

Time:04-25

I have an array of months:

const monthsArr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];  

Also I have two dates: 2021-09-07 and 2022-03-17 . To get the number of the months between these dates I use function:

function monthDiff(dateFrom, dateTo) {
    return dateTo.getMonth() - dateFrom.getMonth()   12 * (dateTo.getFullYear() - dateFrom.getFullYear());
}

How to display all months from the array monthsArr between those two dates? Thanks in advance for any help.

CodePudding user response:

You could use Array().fill() to generate all 12 months for all involved years, flatten that, and then slice the relevant part from it. To make sure that the second argument of slice will be a negative (not zero!), even add 12 more months to that. The second argument will then be a value between -23 and -12:

const monthsArr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];  

function monthsBetween(dateFrom, dateTo) {
    return Array(dateTo.getFullYear() - dateFrom.getFullYear()   2)
           .fill(monthsArr).flat()
           .slice(dateFrom.getMonth(), dateTo.getMonth() - 23);
}

let dateFrom = new Date("2021-09-07");
let dateTo = new Date("2022-03-17");

console.log(monthsBetween(dateFrom, dateTo));

CodePudding user response:

You might find useful to use a utility library such as date-fns (https://date-fns.org/), more specifically the sub function (https://date-fns.org/v2.28.0/docs/sub)

  • Related