Jane Doe Jane Doe - 2 months ago 14
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:

[
"2017-08-21T19:37:09-04:00",
"2017-08-22T19:37:09-04:00",
"2017-08-23T19:37:09-04:00",
"2017-08-24T19:37:09-04:00",
"2017-08-25T19:37:09-04:00",
"2017-08-26T19:37:09-04:00",
"2017-08-27T19:37:09-04:00"
]


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

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));
dateRange.push(moment(date).format());
console.log(dateRange);
}
}


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:

2017-07-31T19:44:06-04:00
2017-08-01T19:44:06-04:00
2017-09-02T19:44:06-04:00
2017-10-04T19:44:06-04:00
2017-11-04T19:44:06-04:00
2017-12-06T19:44:06-04:00
2018-01-06T19:44:06-04:00


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?

Thanks!

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