Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all sundays/mondays/tuesdays between two dates? [duplicate]

Given a start date and an end date, how can I get all the, e.g. Sundays between September 1st and November 2nd?

Note - not a duplicate: I don't want a count, but rather the individual dates as either javascript dates or momentjs objects (The answer linked in the other SO question is asking for a count)

like image 700
CheapSteaks Avatar asked Dec 17 '16 00:12

CheapSteaks


2 Answers

Use a loop to continually get the date for next Sunday until you pass the ending date.

var start = moment('2016-09-01'), // Sept. 1st
    end   = moment('2016-11-02'), // Nov. 2nd
    day   = 0;                    // Sunday

var result = [];
var current = start.clone();

while (current.day(7 + day).isBefore(end)) {
  result.push(current.clone());
}

console.log(result.map(m => m.format('LLLL')));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
like image 186
4castle Avatar answered Nov 15 '22 08:11

4castle


You can go from the start date to the nearest day of the required name, then just keep adding 7 days until you're past the end date, e.g.

/* Given a start date, end date and day name, return
** an array of dates between the two dates for the
** given day inclusive
** @param {Date} start - date to start from
** @param {Date} end - date to end on
** @param {string} dayName - name of day
** @returns {Array} array of Dates
*/
function getDaysBetweenDates(start, end, dayName) {
  var result = [];
  var days = {sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6};
  var day = days[dayName.toLowerCase().substr(0,3)];
  // Copy start date
  var current = new Date(start);
  // Shift to next of required days
  current.setDate(current.getDate() + (day - current.getDay() + 7) % 7);
  // While less than end date, add dates to result array
  while (current < end) {
    result.push(new Date(+current));
    current.setDate(current.getDate() + 7);
  }
  return result;  
}

// Get Wednesdays between 15 December, 2016 and 25 February, 2017.
console.log(getDaysBetweenDates(
              new Date(2016,11,15),
              new Date(2017,1,25),
              'Wed'));

Note that the SO console prints dates as ISO 8601 UTC by default so users east of Greenwich will see dates one day earlier than expected. Also, the function should validate the input, i.e. check that it has valid start and end Date objects and that the dayName is valid.

like image 22
RobG Avatar answered Nov 15 '22 10:11

RobG