Categories
JavaScript Answers

How to enumerate dates between two dates in Moment and JavaScript?

Spread the love

Sometimes, we want to enumerate dates between two dates in Moment and JavaScript.

In this article, we’ll look at how to enumerate dates between two dates in Moment and JavaScript.

How to enumerate dates between two dates in Moment and JavaScript?

To enumerate dates between two dates in Moment and JavaScript, we use a while loop.

For instance, we write

const enumerateDaysBetweenDates = (startDate, endDate) => {
  const now = startDate.clone();
  const dates = [];

  while (now.isSameOrBefore(endDate)) {
    dates.push(now.format("M/D/YYYY"));
    now.add(1, "days");
  }
  return dates;
};

to define the enumerateDaysBetweenDates function.

In it, we clone startDate with clone.

And then we call now.isSameOrBefore with endDate to check if now is before or same as endDate.

If it is, the while loop runs.

In it, we call dates.push to push the now date formatted into a string into dates.

Then we call now.add to add day tonow`.

Finally, we return the dates array.

Conclusion

To enumerate dates between two dates in Moment and JavaScript, we use a while loop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *