How to calculate the number of months between two dates in JavaScript

In this Article we will go through how to calculate the number of months between two dates only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const monthDiff = (startDate, endDate) => Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());

#Example

monthDiff(new Date('2020-01-01'), new Date('2021-01-01'));  // 12