3

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.

Dinesh Madanlal
  • 337
  • 4
  • 20
  • you can convert these date into timestamps, and calculate average from it, then convert result into date – ekans Mar 09 '20 at 13:29
  • Could you please elaborate @ekans? – Dinesh Madanlal Mar 09 '20 at 13:35
  • How are the dates stored? as a set, as a string or as an object? Have you tried converting all of them into days? So multiplying the month value with 30, and adding it to the days. In your case, (30 + (11*30)) + (31 + (0*30)) + (2 + (2*30)) = 422, 422/3 = 140 days = July 20th. – Kenta Nomoto Mar 09 '20 at 13:40
  • Check here = https://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript. – MonteCristo Mar 09 '20 at 13:42
  • 1
    *"should be around 1st of the month."*: which month? Can you be *exact* about your expected output? Secondly, you omitted the year part of your input dates. Is that part not significant? – trincot Mar 09 '20 at 13:46
  • @DineshMadhanlal you can do somthing like that : `const average = ( moment('2019-12-31').unix() + moment('2020-01-31').unix() + moment('2020-03-02').unix() ) \ 3;` then `moment(average)` that will do the trick ! – ekans Mar 09 '20 at 13:49

1 Answers1

0

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') );
Niels Prins
  • 535
  • 2
  • 11