Add getMonthsDiffBetweenDates

This commit is contained in:
Angelos Chalaris
2020-08-07 15:15:26 +03:00
parent 1985355def
commit 0395fde19a

View File

@ -0,0 +1,22 @@
---
title: getMonthsDiffBetweenDates
tags: date,intermediate
---
Returns the difference (in months) between two dates.
Use `Date.prototype.getFullYear()` and `Date.prototype.getMonth()` to calculate the difference (in months) between two `Date` objects.
```js
const getMonthsDiffBetweenDates = (dateInitial, dateFinal) =>
Math.max(
(dateFinal.getFullYear() - dateInitial.getFullYear()) * 12 +
dateFinal.getMonth() -
dateInitial.getMonth(),
0
);
```
```js
getMonthsDiffBetweenDates(new Date('2017-12-13'), new Date('2018-04-29')); // 4
```