Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: get Monday and Sunday of the previous week

Tags:

javascript

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?

like image 419
user18577 Avatar asked Dec 03 '12 10:12

user18577


People also ask

How do I find previous Monday 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.

How do I get last week in JavaScript?

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.


1 Answers

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
like image 91
RobG Avatar answered Sep 29 '22 03:09

RobG