Hi Friends đź‘‹,

Welcome To Infinitbility! âť¤ď¸Ź

To get months between two dates,

1. Use the `getMonth()` method to get the months of both dates, and subtract them to get the difference of months
2. Use the `getFullYear()` method to get the years of both dates, and subtract them to get the difference of years
3. Multiply the year difference by 12 and return the sum.

It will return your difference of dates in months.

The `getMonth()` method returns the month on the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).

The `getFullYear()` method returns the year of the specified date according to local time.

Today, Iâ€™m going to show How do I get months between two dates in javascript, here I will use the javascript `getMonth()` method and `getFullYear()` method to get difference numbers of months.

Letâ€™s start the todayâ€™s tutorial How do you get months between two dates in javascript?

In the following example, we are going to do

1. create two dates starting and ending date
2. create a function that accepts a date and returns months
3. Use a function for multiple date examples

letâ€™s write the code.

``````function getMonths(startDate, endDate) {
return (endDate.getMonth() - startDate.getMonth() + 12 * (endDate.getFullYear() - startDate.getFullYear()));
}

// đź‘‡ď¸Ź 2
console.log(getMonths(new Date('2022-01-15'), new Date('2022-03-16')));

// đź‘‡ď¸Ź 5
console.log(getMonths(new Date('2022-01-15'), new Date('2022-06-16')));

// đź‘‡ď¸Ź 14
console.log(getMonths(new Date('2022-01-15'), new Date('2023-03-16')));
``````

In the above program, we have created a custom function `getMonths()` and pass dates to get a mumber of months.

letâ€™s check the output.