如何获取一周中给定日期的两个日期之间的所有日期?

时间:2019-12-14 16:08:04

标签: javascript

首先,我知道这个问题与这个问题非常相似: How to get all sundays/mondays/tuesdays between two dates?

我要问的是不同的,我试图创建一个函数,其中星期几是变量,并且可以有多个,就像这样:

function findClassDays(daysOfWeek, firstDay, lastDay) {
  const classDays = [];

  return classDays;
}

firstDaylastDay是javascript日期,而daysOfWeek是一个数组,其中包含以ddd moment格式的星期几(例如,数组可以为['Mon', 'Wed', 'Fri']

如果一周中的日期之前未知,并且可能有多个日期,我怎么能找到属于daysOfWeek的两个日期之间的所有日期?我在链接的问题上看到了当您知道日期时它是如何工作的,并且只有一天,但是如果数组具有日期的任何组合,我将找不到解决方案。

2 个答案:

答案 0 :(得分:1)

试穿以获取尺寸:

function findClassDays(daysOfWeek, firstDay, lastDay) {
    var allDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

    //get indices of days provided
    var firstDayIndex = firstDay.getDay();
    var lastDayIndex = lastDay.getDay();

    //determine which days are acceptable
    var acceptableDays = [];
    for(var i = firstDayIndex; i != lastDayIndex; i = (i + 1) % allDays.length){
        acceptableDays[acceptableDays.length] = allDays[i];
    }
    acceptableDays[acceptableDays.length] = allDays[lastDayIndex];

    //return the intersection (overlap) of daysOfWeek and acceptableDays
    return daysOfWeek.filter(function(d){return acceptableDays.indexOf(d) > -1;});
}

或者,如果您需要实际的日期对象,而不仅仅是星期几作为字符串:

function findClassDays(daysOfWeek, firstDay, lastDay){
    var allDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

    var matchingDates = [];
    while(firstDay.getDay() != lastDay.getDay()){
        //if firstDay is in daysOfWeek
        if(daysOfWeek.indexOf(allDays[firstDay.getDay()]) > -1){
            //add it to matchingDates
            matchingDates[matchingDates.length] = firstDay;
        }

        //increment first day
        firstDay = new Date(firstDay.getTime() + 1000 * 60 * 60 * 24);
    }
    //don't forget to check the last day as well
    if(daysOfWeek.indexOf(allDays[lastDay.getDay()]) > -1){
        matchingDates[matchingDates.length] = firstDay;
    }

    return matchingDates;
}

答案 1 :(得分:1)

基于@JohnHartsock的答案,我们可以创建以下函数

  • 填充firstDaylastDay之间的日期范围
  • 根据daysOfWeek
  • 过滤日期

var days = {Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri:5, Sat:6};

function findClassDays(daysOfWeek, firstDay, lastDay) {
  let classDays = [];
  let rangeDates = getDates(new Date(firstDay), new Date(lastDay));
  classDays = rangeDates.filter(f => daysOfWeek.some((d, i) => days[d]== f.getDay()));
  return classDays;
}

function getDates(startDate, stopDate) {
  var dateArray = new Array();
  var currentDate = new Date(startDate);
  while (currentDate <= stopDate) {
      dateArray.push(new Date (currentDate));
      currentDate = currentDate.addDays(1);
  }
  return dateArray;
}

Date.prototype.addDays = function(days) {
  var date = new Date(this.valueOf());
  date.setDate(date.getDate() + days);
  return date;
}

console.log(findClassDays(['Mon', 'Wed', 'Fri'], '2019-12-01', '2019-12-15'));