Date Range Generator

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be exploring how to create a date range generator using JavaScript. This generator will allow us to easily generate all dates within a specified range using a given step. By using the Date constructor and yield keyword, we can efficiently iterate over the dates and return them to the user. This lab will be a great opportunity to practice working with loops and dates in JavaScript.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

Date Range Generator

To generate all dates in a given range using a given step, use the following code in Terminal/SSH and type node:

const dateRangeGenerator = function* (start, end, step = 1) {
  let d = start;
  while (d < end) {
    yield new Date(d);
    d.setDate(d.getDate() + step);
  }
};

This creates a generator that uses a while loop to iterate from start to end, using Date constructor to return each date in the range and increments by step days using Date.prototype.getDate() and Date.prototype.setDate().

To use a default value of 1 for step, omit the third argument.

Here's an example of how to use the dateRangeGenerator:

[...dateRangeGenerator(new Date("2021-06-01"), new Date("2021-06-04"))];
// [ 2021-06-01, 2021-06-02, 2021-06-03 ]

Summary

Congratulations! You have completed the Date Range Generator lab. You can practice more labs in LabEx to improve your skills.