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.

javascript, get months between two dates example
javascript, get months between two dates example

I hope it’s help you, All the best 👍.