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

那年仲夏 提交于 2019-12-30 10:26:35

问题


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)


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/41194368/how-to-get-all-sundays-mondays-tuesdays-between-two-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!