Date Range Generator

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28248{{"`Date Range Generator`"}} javascript/data_types -.-> lab-28248{{"`Date Range Generator`"}} javascript/arith_ops -.-> lab-28248{{"`Date Range Generator`"}} javascript/comp_ops -.-> lab-28248{{"`Date Range Generator`"}} javascript/loops -.-> lab-28248{{"`Date Range Generator`"}} javascript/spread_rest -.-> lab-28248{{"`Date Range Generator`"}} end

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.

Other JavaScript Tutorials you may like