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?
To get the date of the previous Monday: Add 6 to the day of the week and get the remainder of dividing by 7 . Subtract the result from the day of the month.
To get last week's date, use the Date() constructor to create a new date, passing it the year, month and the day of the month - 7 to get the date of a week ago. Copied! function getLastWeeksDate() { const now = new Date(); return new Date(now.
You can get the previous Monday by getting the Monday of this week and subtracting 7 days. The Sunday will be one day before that, so:
var d = new Date();
// set to Monday of this week
d.setDate(d.getDate() - (d.getDay() + 6) % 7);
// set to previous Monday
d.setDate(d.getDate() - 7);
// create new date of day before
var sunday = new Date(d.getFullYear(), d.getMonth(), d.getDate() - 1);
For 2012-12-03 I get:
Mon 26 Nov 2012
Sun 25 Nov 2012
Is that what you want?
// Or new date for the following Sunday
var sunday = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 6);
which gives
Sun 02 Dec 2012
In general, you can manipulate date objects by add and subtracting years, months and days. The object will handle negative values automatically, e.g.
var d = new Date(2012,11,0)
Will create a date for 2012-11-30 (noting that months are zero based so 11 is December). Also:
d.setMonth(d.getMonth() - 1); // 2012-10-30
d.setDate(d.getDate() - 30); // 2012-09-30
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With