C
C
coder562020-07-16 11:09:45
JavaScript
coder56, 2020-07-16 11:09:45

How to find the difference between two dates in months?

Find the difference between two dates in months. There is a solution:

let date1 = new Date(1980,01,26,23,59,59);
let date2 = new Date(2020,07,16,23,59,59);
let diff = date1.getTime() - date2.getTime();
console.log(diff/(1000 * 60 * 60 * 24 * 31 ));

But it does not quite fit, because a month can have 30 and 28 and 29 days. What methods can be used to solve this problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2020-07-16
@coder56

momentjs

C
coder56, 2020-07-16
@coder56

let date1 = new Date(1980,01,26,23,59,59);
let date2 = new Date(2020,07,16,23,59,59);
let diff = (date2.getDate() - date1.getDate()) / 30 +
date2.getMonth() - date1.getMonth() +
(12 * (date2.getFullYear() - date1.getFullYear()));
console log(diff);
Or so, if you do not use moment js.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question