Jane Doe Jane Doe - 10 months ago 58
jQuery Question

Get monday-sunday based off of a given date

So I have function that receives a date and returns every day from the week that that date is in from Monday to Sunday.

So for instance:

input into function: 2017-08-24T19:37:09-04:00

would return an array of:


Here is the code I have so far (I'm using

function getMonday(d) {
d = new Date(d);
var day = d.getDay() || 7;
var diff = d.getDate() - day + (day == 0 ? -6:1);
for (var i = 0; i <= 6; i++) {
var date = new Date(d.setDate(diff+i));

So this works fine, but it fails when the input is:
getMonday(new Date('2017-07-31T19:44:06-04:00'))

In this instance it returns:


Which is obviously wrong as it is incrementing the months...

What's going on? Is there a way to easily fix this that I'm missing?


Answer Source

The problem appears to be that you are mutating d by diff + i in each loop which, given an original day-of-month of say 31, ends up bumping d up by around a month each time.

Something like this should be simpler

function getMonday(inputDate) {
  let d = new Date(inputDate)
  let out = []
  // set to "Sunday" for the previous week
  d.setDate(d.getDate() - (d.getDay() || 7)) // if getDay is 0 (Sunday), take 7 days
  for (let i = 0; i < 7; i++) { // note, the value of i is unused
    out.push(new Date(d.setDate(d.getDate() + 1))) // increment by one day
  return out

const input = '2017-08-27T19:44:06'
console.info(getMonday(input).map(d => d.toString()))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download