'Calculate middle date

I want to calculate the middle between two dates in Javascript. So I tried:

var middate = (startdate+enddate)/2;
console.log(middate);

which logs

NaN

What is the problem?



Solution 1:[1]

"Middle of two dates" is not unambiguously defined - you must decide how to handle dates an odd number of days apart (e.g. what is the middle date between 1st and 4th of a month, or between 1st and 2nd), and what to do with the time portion of the date object.

The concrete problem with your approach is that dates are not numbers, so you cannot add them and divide them by two. To do that, use the getTime() method to obtain the number of seconds since the epoch, and operate on that:

var middate = new Date((startdate.getTime() + enddate.getTime()) / 2);

This will give you the middle between two dates, treating them as points in time.

Solution 2:[2]

Try something like this:

date1 = new Date("Feb 10 2014")
date2 = new Date("Feb 12 2014")
middle = new Date(date2 - (date2-date1)/2);
console.log(middle);

Solution 3:[3]

using moment js you can do this like this.

const getMidTimeBetweenTwoDate = (date1, date2) => {
  let date1Moment = moment(date1);
  let date2Moment = moment(date2);
  let diff = date2Moment.diff(date1Moment, 'minutes');
  let midTime = date1Moment.add(diff/2, 'minutes');
  return midTime;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 user1578653
Solution 3 MD. IBRAHIM KHALIL TANIM