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



首先,我知道这个问题与这个问题非常相似: 如何在两个日期之间获得所有周日/周一/周二?

不过,我问的是不同的,我正在尝试创建一个函数,其中星期几是一个变量,并且可以有多个变量,如下所示:

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

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

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

根据@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'));

试试这个大小:

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;
}

最新更新