Borislav Hadzhiev
Mon Jan 17 2022·2 min read
Photo by Gordon Plant
To get the number of months between 2 dates:
getMonth()
method to calculate the month difference between the two
dates.getFullYear()
method to calculate the difference in years between
the dates.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.
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.