How to get a date range using moment.js and JavaScript?

Sometimes, we want to get a date range using moment.js and JavaScript.

In this article, we’ll look at how to get a date range using moment.js and JavaScript.

How to get a date range using moment.js and JavaScript?

To get a date range using moment.js and JavaScript, we can use the moment add method.

For instance, we write:

const startDate = moment('2022-01-01')
const endDate = moment('2022-01-21')
let d = startDate
const range = []
while (+d.toDate() < +endDate.toDate()) {
  range.push(d.toDate())
  d = d.add(1, 'days')
}
console.log(range)

to set the start and end date of the range to startDate and endDate.

Then we set d to startDate.

Next, we use a while loop that runs until d is later than endDate.

In the loop, we call range.push with d.toDate() to push the moment object d converted to a date.

Then we call add with 1 and 'days' to add one day.

Therefore, range is has the dates from Jan 1, 2022 to Jan 20, 2022.

Conclusion

To get a date range using moment.js and JavaScript, we can use the moment add method.