/

How to Calculate the Days Between Two Dates in JavaScript

How to Calculate the Days Between Two Dates in JavaScript

If you are working with JavaScript and need to calculate the number of days between two given dates, you can use the following function. This function takes two JavaScript Date objects as parameters and returns an array of Date objects, representing each day between the two dates.

1
2
3
4
5
6
7
8
9
10
11
12
const getDatesBetweenDates = (startDate, endDate) => {
let dates = []; // initialize an empty array to store the dates
const theDate = new Date(startDate); // create a copy of the start date to avoid modification

while (theDate < endDate) {
// add the current date to the array
dates = [...dates, new Date(theDate)];
theDate.setDate(theDate.getDate() + 1); // increment the date by one day
}

return dates; // return the array of dates
};

You can use the function like this:

1
2
3
4
5
6
7
const today = new Date(); // get the current date
const threeDaysFromNow = new Date(today);
threeDaysFromNow.setDate(threeDaysFromNow.getDate() + 3); // add three days to the current date

const datesBetween = getDatesBetweenDates(today, threeDaysFromNow);

console.log(datesBetween);

If you also want to include the start and end dates in the resulting array, you can use this modified version of the function:

1
2
3
4
5
6
7
8
9
10
11
const getDatesBetweenDates = (startDate, endDate) => {
let dates = [];
const theDate = new Date(startDate);

while (theDate <= endDate) { // change the condition to include the end date
dates = [...dates, new Date(theDate)];
theDate.setDate(theDate.getDate() + 1);
}

return dates;
};

Using this updated version, the resulting array will contain both the start and end dates.

To summarize, with the provided function, you can easily calculate the days between two dates in JavaScript. It gives you a convenient way to generate an array of Date objects representing each day between the start and end dates.

tags: [“JavaScript”, “Date objects”, “calculate days”]