How to find average number of days for the given dates?

Viewed 163

Trying to solve a problem(javascript, moment)

Let's say there are three days, 30th Dec, 31st Jan and 2nd March.

I want to be able to calculate an average number of days between the three, i.e from observation should be around 1st of the month.

However, I can't do that with basic maths adding all 3 and dividing by 3 as months are cyclic.

1 Answers

You can use this: JSFiddle

var dates = [
    '12/30/2019',
    '01/31/2020',
    '03/02/2020',
];

var sum = 0;
dates.forEach(function(date) {
    sum += moment(date).unix()
});

var avarage_date = sum / dates.length * 1000;
console.log( moment(avarage_date).format('MM-DD-YYYY') );
Related