Categories
JavaScript Answers

How to get difference in months between two dates in JavaScript?

Spread the love

Sometimes, we want to get difference in months between two dates in JavaScript.

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

How to get difference in months between two dates in JavaScript?

To get difference in months between two dates in JavaScript, we subtract the months from the 2 dates.

Then we add back the number of years difference converted to months.

For instance, we write

const monthDiff = (dateFrom, dateTo) => {
  return (
    dateTo.getMonth() -
    dateFrom.getMonth() +
    12 * (dateTo.getFullYear() - dateFrom.getFullYear())
  );
};

to get the monthDiff function.

In it, we call getMonth to get the months.

We get the difference with

dateTo.getMonth() - dateFrom.getMonth()

And we add the years difference with

12 * (dateTo.getFullYear() - dateFrom.getFullYear()

Conclusion

To get difference in months between two dates in JavaScript, we subtract the months from the 2 dates.

Then we add back the number of years difference converted to months.

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 *