In this article, we will discuss how to calculate the number of days between two dates in JavaScript.

By using the Date object in the JavaScript we can easily achieve this task.

Following is the example of how to calculate the no of days between two dates using the javascript

function getDaysBetweenDates(startDate, endDate) {
  const timeDiff = endDate.getTime() - startDate.getTime();
  const daysDiff = Math.ceil(timeDiff / 86400000);
  return daysDiff;
}

const startDate = new Date('2022-01-01');
const endDate = new Date('2022-03-28');
const daysDiff = getDaysBetweenDates(startDate, endDate);
console.log(daysDiff);

Explanation

In the above example, Using the date object we defined the start and end date between which we want to find the no of days.

We got the milliseconds difference between those two dates by subtracting the start date from the end date and dividing this value with no of milliseconds per day i.e. 86400000 gives us the total no of days between those two dates.

By using the Math.ceil() function we can round up the result to the nearest integer, as we want to count the no of days including the start and end date

Finally, we displayed the result using the console.log().

Categorized in:

Tagged in: