JavaScript: how to create a date range

JavaScript: how to create a date range

Date ranges are quite easy to create with JavaScript.

Date ranges are quite easy to create with JavaScript.

The first thing we need to do is to understand that the base unit for calculating dates are milliseconds. Since we want to return days, we need to calculate how many milliseconds are contained in a single day.

Days, in turn, are made up of hours, minutes and seconds. There are 24 hours in a day, 60 minutes in an hour and 60 seconds in a minute. Finally, one second equals to 1000 milliseconds.

So we can write the following code:


'use strict';

const dateRange = ( start = new Date(), days = 10) => {
    const dayMs = 1000 * 60 * 60 * 24;
    let startTimestamp = start.getTime();
    let range = [];

    for(let i = 0; i < days; i++) {
        startTimestamp += dayMs;
        range.push(new Date(startTimestamp));
    }
    return range;
};

You can see the above code in action on the following page.