Javascript: get Monday and Sunday of the previous week

You could use a library like moment.js. See the subtract method http://momentjs.com/docs/#/manipulating/subtract/


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));

A few answers mentioned moment, but no one wrote about this simple method:

moment().day(-13) // Monday last week
moment().day(-7) // Sunday last week

.day sets a week day, so it doesn't matter what day is it today, only week matters.


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

Tags:

Javascript