Javascript: get Monday and Sunday of the previous week
javascript
Solution
if you dont want to do it with an external library you should work with timestamps. i created a solution where you would substract 60*60*24*7*1000 (which is 604800000, which is 1 week in milliseconds) from the current Date and go from there:
var beforeOneWeek = new Date(new Date().getTime() - 60 * 60 * 24 * 7 * 1000)
, day = beforeOneWeek.getDay()
, diffToMonday = beforeOneWeek.getDate() - day + (day === 0 ? -6 : 1)
, lastMonday = new Date(beforeOneWeek.setDate(diffToMonday))
, lastSunday = new Date(beforeOneWeek.setDate(diffToMonday + 6));
Problem
I am using the following script to get Monday (first) and Sunday (last) for the previous week: ``` var curr = new Date; // get current date var first = curr.getDate() - curr.getDay() - 6; // Gets day of the month (e.g. 21) - the day of the week (e.g. wednesday = 3) = Sunday (18th) - 6 var last = first + 6; // last day is the first day + 6 var startDate = new Date(curr.setDate(first)); var endDate = new Date(curr.setDate(last)); ``` This works fine if last Monday and Sunday were also in the same month, but I just noticed today that it doesn't work if today is December and last Monday was in November. I'm a total JS novice, is there another way to get these dates?