I need an array of recurring dates with time for every week within the start date and end date using moment.js or javascript.
For example: Startdate: 2021-10-04T00:00:00Z Enddate: 2021-10-31T00:00:00Z
let's say 2021-10-05T00:00:00Z is a recurring date then output will be
["2021-10-05T00:00:00Z", "2021-10-12T00:00:00Z", "2021-10-19T00:00:00Z", "2021-10-26T00:00:00Z"]
CodePudding user response:
We can use Date.getUTCDate()
and Date.setUTCDate()
to advance a date by a number of days, in this case seven.
We can then use a while loop to populate the result array. I'm returning an array of Date objects here, one could use .toISOString() to convert to strings.
let startDate = '2021-10-05T00:00:00Z';
let endDate = '2021-10-31T00:00:00Z';
function getWeeklyDates(start, end) {
let date = new Date(start);
const endDate = new Date(end);
const result = [];
while (date < endDate) {
result.push(date);
date = new Date(date);
date.setUTCDate(date.getUTCDate() 7);
}
return result;
}
console.log(getWeeklyDates(startDate, endDate).map(dt => dt.toISOString()))
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
You can do this with pure js if you remove the "Z" add " 00:00" to all of your strings to make sure your timezone does not break this code.
let start = "2021-10-04T00:00:00 00:00";
let end = "2021-10-31T00:00:00 00:00";
let date = "2021-10-05T00:00:00 00:00";
start = new Date(start);
end = new Date(end);
date = new Date(date);
let dates = [];
if (date < start) {
console.log("bad input")
} else {
while (date.getTime() < end.getTime()) {
dates.push(date.toISOString());
date = new Date(date.getTime() 604800000); // add a week in milliseconds
}
}
CodePudding user response:
you can do something like:
- start at the first recurring date
- add a week to the recurring date using
.add(1, 'weeks')
(see https://momentjs.com/docs/#/manipulating/add/ ) - do this while recurring date < end date