How to Get the Number of Months Between Two Dates in JavaScript

1. Date getMonth() method

To get the number of months between two dates in JavaScript:

  1. Use date1.getMonth() - date2.getMonth() to get the month difference between the two dates.
  2. Use date1.getYear() - date2.getYear() to get the difference between the two dates.
  3. Add the month difference to the year difference multiplied by 12, i.e, monthDiff + yearDiff * 12.

For example:

JavaScript
function differenceInMonths(date1, date2) { const monthDiff = date1.getMonth() - date2.getMonth(); const yearDiff = date1.getYear() - date2.getYear(); return monthDiff + yearDiff * 12; } // June 5, 2022 const date1 = new Date('2022-06-05'); // March 17, 2021 const date2 = new Date('2021-03-17'); const difference = differenceInMonths(date1, date2); console.log(difference); // 15

Our reusable differenceInMonths() function takes two Date objects and returns the difference in months between them. The first argument is the start date, and the second is the end date.

The Date getMonth() method returns a zero-based number that represents the month of a particular date.

Note: “Zero-based” here means that 0 is January, 1 is February, 2 is March, etc.

Apart from subtracting the months, we also need to subtract the years, because the two dates might have different years, and this would of course affect the number of months between them. We use the getFullYear() method to get the years of the dates and subtract them.

The Date getFullYear() method returns a number that represents the year of a particular date.

A year equals 12 months, so after getting the year difference, we multiple it by 12 to get the equivalent months, and add it to the month difference.

2. date-fns differenceInMonths() function

Alternative we can use the differenceInMonths() function from the date-fns NPM package to quickly get the difference in months between two dates in JavaScript. It works just like our own differenceInMonths() function, taking two Date objects and returning the difference in their months.

JavaScript
import { differenceInMonths } from 'date-fns'; const date1 = new Date('2022-08-10'); const date2 = new Date('2020-02-24'); const difference = differenceInMonths(date1, date2); console.log(difference); // 29


11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *