Files
30-seconds-of-code/snippets/getMonthsDiffBetweenDates.md
Isabelle Viktoria Maciohsek 920a0c390b Update snippet descriptions
2020-10-19 22:49:51 +03:00

23 lines
572 B
Markdown

---
title: getMonthsDiffBetweenDates
tags: date,intermediate
---
Calculates 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
```