The code:
function getPreviousSunday() { var today=new Date(); return new Date().setDate(today.getDate()-today.getDay()-7); } function getPreviousMonday() { var today=new Date(); if(today.getDay() != 0) return new Date().setDate(today.getDate()-7-6); else return new Date().setDate(today.getDate()-today.getDay()-6); }
Reasoning:
Depends on what you mean the previous day on the first day. I assume that you mean the previous Sunday for this discussion.
To find the number of days to deduct:
- Get the current day of the week.
- If the current day of the week is Sunday, you subtract 7 days
- If the current day is Monday, you subtract 8 days
...
- If the current day is Saturday 13 days
The actual code, once you determine the number of days to deduct, is easy:
var previous_first_day_of_week=new Date().setDate(today.getDate()-X);
Where X is the above value. This value is today.getDay () + 7
If you meant something else on the first day of the week, you should be able to deduce the answer from the steps above.
Note. Indeed, to pass negative values ββto the setDate function, it will work correctly.
Code on Monday. You have this special case, because getDay () orders are Sunday through Monday. Thus, we basically replace getDay () in this case with the value of getDay () equal to half a day + 1, for re-ordering Sunday until the end of the week.
We use a value of 6 to subtract from Monday, because getDay () returns 1 more for each day than we want.
source share