When working with dates in JavaScript, you might come across the need to calculate the number of days between two dates. This can be particularly useful, for example, when determining the duration of a rental stay based on the check-in and check-out dates.

After exploring different solutions, I found a reliable approach that takes into account common date-related issues, such as Daylight Saving Time (DST). The method involves incrementing the start date by one day until it exceeds the end date.

Here’s the code snippet that accomplishes this:

const numberOfNightsBetweenDates = (startDate, endDate) => {
    const start = new Date(startDate); // clone
    const end = new Date(endDate); // clone
    let dayCount = 0;

    while (end > start) {
        dayCount++;
        start.setDate(start.getDate() + 1);
    }

    return dayCount;
};

In this code, we begin by creating clones of the given start and end dates. It’s important to clone the dates since the setDate() method can modify the original objects, which is not desirable.

That’s all there is to it! This function effectively calculates the number of nights between two dates. If you need to calculate the number of days instead, simply modify the condition in the while loop from end > start to end >= start. Alternatively, you can start the dayCount variable at 1.

Tags: JavaScript, date calculation, number of days, clone dates, while loop