Mahesh
Mahesh

Reputation: 221

How to get recurring dates using moment

In my scenario I have an start date and end date

const startDate = 2018-11-07  // YYYY-MM-DD format and it is Wednesday

const endDate = 2018-12-01

I am getting a flag from UI where event need to be repeated weekly from start date to end date

How can I get event dates that fall in that range?

Expecting result approx to ["2018-11-07", "2018-11-14", .... ,"2018-11-28"]

Upvotes: 0

Views: 1190

Answers (2)

Akrion
Akrion

Reputation: 18525

You can simply utilize the official moment plugin moment-range:

const Moment = require('moment');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);

const range = moment.range(moment('2018-11-07'), moment('2018-12-01'));

console.log(Array.from(range.by('week')))

Outputs:

[ moment("2018-11-07T00:00:00.000"),
  moment("2018-11-14T00:00:00.000"),
  moment("2018-11-21T00:00:00.000"),
  moment("2018-11-28T00:00:00.000") ]

Upvotes: 3

num8er
num8er

Reputation: 19372

You can use moment-range as Akrion mentioned.

But You can simply make Your own helper method.

Take it:

const moment = require('moment');

const generateDateRange = (from, to, step = 1, modifier = 'day', format = 'YYYY-MM-DD') => {
  const dates = [];

  let currentDate = moment(from);
  const lastDate = moment(to);

  while(currentDate <= lastDate) {
    dates.push(currentDate.format(format));
    currentDate = currentDate.add(step, modifier);
  }

  return dates;
}


const dates = generateDateRange('2018-11-07', '2018-12-01', 1, 'week');
console.log(dates);

Test here

Upvotes: 0

Related Questions