Get the Number of Months between 2 Dates in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 between 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 are in the same year).
index.js
function getMonthDifference(startDate, endDate) { return ( endDate.getMonth() - startDate.getMonth() + 12 * (endDate.getFullYear() - startDate.getFullYear()) ); }

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.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.