Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display months between two dates with different years

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading