Categories
JavaScript Answers

How to Get the Difference in Months Between Two Dates in JavaScript?

Spread the love

Sometimes, we want to get the difference in months between 2 dates in our JavaScript code.

In this article, we’ll look at how to get the difference between 2 dates in months with JavaScript.

Get the Month Difference Between the 2 Dates

We can calculate the month difference between 2 dates, then get the month difference based on the year difference.

Then we multiply the year difference by 12 to convert that to months.

Then we subtract the month from the start date.

And then we add the month from the end date.

To do this, we write:

const monthDiff = (d1, d2) => {
  let months;
  months = (d2.getFullYear() - d1.getFullYear()) * 12;
  months -= d1.getMonth();
  months += d2.getMonth();
  return months <= 0 ? 0 : months;
}

const start = new Date(2020, 1, 1)
const end = new Date(2020, 5, 1)
console.log(monthDiff(start, end))

We first get the year difference and convert that to months with:

months = (d2.getFullYear() - d1.getFullYear()) * 12;

Then we subtract the month of d1 with:

months -= d1.getMonth();

Then we add the months from d2 with:

months += d2.getMonth();

And then we return months if it’s bigger than 0.

Otherwise, we return 0.

Therefore, the console log should log 4 since there’s a 4-month difference between the 2 dates.

Conclusion

We can get the difference between the 2 dates by getting the year difference, converting that to months.

Then we can subtract the number of months from the start dates.

And add the months from the end date to remove double counting.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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