[enter image description here][1]I'm in a situation where i need to find date range of First, Second, Third & Fourth Week (i.e we can say Nth week) in a month. Its a booking website where i want to give an option of creating an event which repeats on every Nth week's Nth days.
E.g
Repeat On - Every Second Week
[1]: https://i.sstatic.net/XysBp.png -- create event
[1]: https://i.sstatic.net/tN8sE.png -- book event
for (var i = range.start.getTime(), end = range.end.getTime(); i <= end;) {
var first = new Date(i);
var last = new Date(first.getFullYear(), first.getMonth() + 1, 0); // last day of the month
if(item.recurring_type == 'every_week') {
// in case of repetition every week
ranges.push({
start: moment(formatDate(first),'YYYY-MM-DD'),
end: moment(formatDate(last),'YYYY-MM-DD').endOf('month'),
})
} else if(item.recurring_type == 'first_week') {
// 1 to 7
var cus_date_start = new Date(first.getFullYear(), first.getMonth(), 1);
var cus_date_end = new Date(first.getFullYear(), first.getMonth(), 7);
if( cus_date_start.getDate() >= first.getDate() && cus_date_end.getDate() <= last.getDate() ) {
ranges.push({
start: moment(formatDate(cus_date_start),'YYYY-MM-DD'),
end: moment(formatDate(cus_date_end),'YYYY-MM-DD'),
})
}
} else if(item.recurring_type == 'second_week') {
// 8 to 14
var cus_date_start = new Date(first.getFullYear(), first.getMonth(), 8);
var cus_date_end = new Date(first.getFullYear(), first.getMonth(), 14);
if( cus_date_start.getDate() >= first.getDate() && cus_date_end.getDate() <= last.getDate() ) {
ranges.push({
start: moment(formatDate(cus_date_start),'YYYY-MM-DD'),
end: moment(formatDate(cus_date_end),'YYYY-MM-DD'),
})
}
} else if(item.recurring_type == 'third_week') {
// 15 to 21
var cus_date_start = new Date(first.getFullYear(), first.getMonth(), 15);
var cus_date_end = new Date(first.getFullYear(), first.getMonth(), 21);
if( cus_date_start.getDate() >= first.getDate() && cus_date_end.getDate() <= last.getDate() ) {
ranges.push({
start: moment(formatDate(cus_date_start),'YYYY-MM-DD'),
end: moment(formatDate(cus_date_end),'YYYY-MM-DD'),
})
}
} else {
// 22 to end
var cus_date_start = new Date(first.getFullYear(), first.getMonth(), 22);
ranges.push({
start: moment(formatDate(cus_date_start),'YYYY-MM-DD'),
end: moment(formatDate(last),'YYYY-MM-DD').endOf('month'),
})
}
i = last.getTime() + aDay;
}
This is the solution i've made that is close but not accurate, if anyone can improve this code then please post your answers.
Thank you