Date range generator

JavaScript, Date, Function, Generator · Jun 21, 2021

Creates a generator, that generates all dates in the given range using the given step.

  • Use a while loop to iterate from start to end, using yield to return each date in the range, using the Date constructor.
  • Use Date.prototype.getDate() and Date.prototype.setDate() to increment by step days after returning each subsequent value.
  • Omit the third argument, step, to use a default value of 1.
const dateRangeGenerator = function* (start, end, step = 1) {
  let d = start;
  while (d < end) {
    yield new Date(d);
    d.setDate(d.getDate() + step);
[...dateRangeGenerator(new Date('2021-06-01'), new Date('2021-06-04'))];
// [ 2021-06-01, 2021-06-02, 2021-06-03 ]

More like this

  • JavaScript Function Snippets

    Learn everything about JavaScript functions with this ES6 snippet collection.

    Collection · 95 snippets

  • Range generator

    Creates a generator, that generates all values in the given range using the given step.

    JavaScript, Function · Oct 11, 2020

  • Check if date is valid

    Checks if a valid date object can be created from the given values.

    JavaScript, Date · Oct 20, 2020

  • Add weekdays to date

    Calculates the date after adding the given number of business days.

    JavaScript, Date · Jan 7, 2021