Answer the question
In order to leave comments, you need to log in
How to display dates in a given range, specific days of the week?
How to display dates of given days of the week before a certain date? For example:
Tuesday + Wednesday: 07/18/17 07/19/17 07/25/17 07/26/17 . . .
Monday + Friday: 07/17/17 07/21/17 07/24/17 07/28/17 . . .
etc.
The days of the week are selected by the user.
Answer the question
In order to leave comments, you need to log in
The Date object 's setDate() method sets the day of the month, updating the month as necessary.
Those. the algorithm is simple: add 7 days to the included days of the week, and read the resulting date.
/**
* Make Dates according to selected days of week till the specified date
* @param Array weekdays: 0 - Sunday, 1 - Monday, ..
* @param Mixed Date or String - last day of range
*
* @return Array of Date objects
*/
function getDates( weekDays, lastDate) {
if(typeof lastDate === 'string') lastDate = new Date(lastDate);
var today = new Date(), dow, i, D, datesPool = [], result = [];
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
dow = today.getDay();
for(i=0; i<7; i++) {
if( !~weekDays.indexOf( (dow + i)%7)) continue;
D = new Date();
D.setTime( today.getTime());
D.setDate( D.getDate() + i);
if( D.getTime() > lastDate.getTime()) continue;
datesPool.push( D);
}
if( datesPool.length === 0) return result;
while(true) {
for( i = 0; i < datesPool.length; i++) {
D = datesPool[i];
if( D.getTime() > lastDate.getTime()) return result;
if( result.length > 1000) return result;
result.push( "" + D.getDate() + "." + (1 + D.getMonth()) + "." + D.getFullYear().toString().substr(2));
D.setDate( D.getDate() + 7);
}
}
}
getDates( [2,3], '2017-07-31') // 19.7.17,25.7.17,26.7.17
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question