Get the Number of Months between 2 Dates in JavaScript

avatar

Borislav Hadzhiev

Mon Jan 17 20222 min read

banner

Photo by Gordon Plant

Get the Number of Months between 2 Dates in JavaScript #

To get the number of months between 2 dates:

  1. Use the getMonth() method to calculate the month difference between the two dates.
  2. Use the getFullYear() method to calculate the difference in years between the dates.
  3. Multiply the year difference by 12 and return the sum.
index.js
function getMonthDifference(startDate, endDate) { return ( endDate.getMonth() - startDate.getMonth() + 12 * (endDate.getFullYear() - startDate.getFullYear()) ); } // 👇️ 2 console.log(getMonthDifference( new Date('2022-01-15'), new Date('2022-03-16')) ); // 👇️ 5 console.log(getMonthDifference( new Date('2022-01-15'), new Date('2022-06-16')) ); // 👇️ 14 console.log(getMonthDifference( new Date('2022-01-15'), new Date('2023-03-16')) );

We created a reusable function that returns the number of months there are between two dates.

The function takes the start and end Date objects as parameters.

The getMonth method returns a zero-based value representing the month of the specific Date.

The method returns an integer from 0 to 11, where January is 0, February is 1, etc.

This doesn't matter for our purposes, but it's good to know when working with dates in JavaScript.

We subtracted the month index of the start date from the month index of the end date, this gets us the number of months between the 2 dates, if the 2 dates were in the same year.

The next step is to account for the possibility where the dates are in different years.

The getFullYear method returns a 4-digit integer representing the year of the date.

We got the difference in years between the two dates and multiplied by 12 to get the difference in months.

The last step is to add the month difference (from the same year) to the result to get the total number of months between the two dates.
Use the search field on my Home Page to filter through my more than 1,000 articles.