In plain terms, you have the ability to specify the day of the week on a Date object in vanilla JavaScript with the following function:
function setDay(d, day, week_starts_monday) {
var c_day = d.getDay();
if (week_starts_monday && c_day === 0)
c_day = 7; // adjust so `0` represents last Sunday, and `7` signifies this Sunday
d.setDate(d.getDate() - c_day + day);
return d;
}
For example, setting a date to represent Monday of the current week given that today is Friday the 27th would look like this:
var d = new Date;
setDay(d, 1); // Mon Nov 23 2015 18:51:45 GMT+0000 (GMT Standard Time)
As a reference point, 7
corresponds to the upcoming Sunday, while 0
signifies the previous Sunday or the present day if it happens to be a Sunday.
setDay(d, 7); // Sun Nov 29 2015 18:51:45 GMT+0000 (GMT Standard Time)
You can now loop through different days using a for
loop as per your requirements,
var i, d = new Date;
for (i = 1; i <= 7; ++i) {
setDay(d, i);
// perform actions with `d`
}
A couple of things to keep in mind:
- When transitioning between timezones, there may be unexpected outcomes. Consider executing this logic in UTC for reliability.
- To go back from Sunday, utilize negative numbers accordingly.