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.
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)
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));
A simplistic approach is to increment the start date by one month at a time and return the value at that index from the array. The only issue is to work out whether "between" includes the start and end month or only those between those months.
The following includes the start and end months in the result:
let months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function getMonthsBetweenDates(startDate, endDate) {
// Make start as 1st of startDate month
let s = new Date(startDate.getFullYear(), startDate.getMonth());
let result = [];
// Loop over months until get to end month
while (s <= endDate) {
result.push(months[s.getMonth()]);
s.setMonth(s.getMonth() + 1);
}
return result;
}
// Get months between 2021-09-07 and 2022-03-17
console.log(getMonthsBetweenDates(new Date(2021,8,7), new Date(2022,2,17)));