Exact Month difference between two dates - MomentJS

Viewed 1549

I need to know the difference between months, but I cannot perform this calculation based on the days, considering that there are months with only 28 days.

I really need to bring the difference between months.

Format: YYYY/DD/MM

Old: 2019/01/19

New: 2020/03/19

Between: 14

Example 01:
Old Date: 19/03/2020
New Date: 31/03/2020
Between: 0

Example: 02:
Old Date: 19/03/2020
New Date: 01/04/2020
Between: 1

Example: 03:
Old Date: 19/03/2020
New Date: 30/04/2020
Between: 1

Example: 04:
Old Date: 19/03/2020
New Date: 01/05/2020
Between: 2

Example: 05:
Old Date: 19/03/2020
New Date: 01/05/2021
Between: 14
1 Answers

You can discard the days count by using momentjs .startOf('month') date modifier and then compare the days using .diff():

const getDate = (date) => moment(date, 'DD/MM/YYYY').startOf('month')
const diff = Math.abs(getDate('19/03/2020').diff(getDate('01/05/2021'), 'months'));

console.log(diff)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Related