根据给定的日期从范围中获取选定的日期

Sto*_*per 5 javascript date

我有一个日期范围

日期范围示例:

const startDate = "2022-06-02";
const endDate = "2022-06-20";
Run Code Online (Sandbox Code Playgroud)

我想获取在 startDate 和 endDate 之间提供的日期数组中出现的日期

天数数组示例:

["tuesday", "friday", "saturday"]
Run Code Online (Sandbox Code Playgroud)

预期结果是:

2022-06-03
2022-06-04
2022-06-07
2022-06-10
2022-06-11
2022-06-14
2022-06-17
2022-06-18
Run Code Online (Sandbox Code Playgroud)

谁能帮我解决这个逻辑?

What I tried was so dirty, I put a loop on range of dates, and got the list of all dates, and then i put another loop to get name of day of each date, and then compared each day name in an array of days & pushed that date to new array

这是代码(工作得很好),但我需要更好的解决方案

function getDaysArray(start, end) {
        
    for(var arr=[],dt=new Date(start); dt<=new Date(end); dt.setDate(dt.getDate()+1)){
        
        arr.push(helperClass.getDateTime(new Date(dt)).date);
    }
    
    return arr;
}

function getDayName (dateStr, locale){

    var date = new Date(dateStr);

    return date.toLocaleDateString(locale, { weekday: 'long' });        
}

var days = ["tuesday", "friday", "saturday"];

var getAllDates = getDaysArray("2022-06-02", "2022-06-20");
var getDates = [];
for(var i = 0; i < getAllDates.length; i++){

    if(days.includes(getDayName(getAllDates[i]).toLowerCase())){

        getDates.push(getAllDates[i])
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 -1

我知道这可能不是最好的方法,但我是这样做的

let days = { monday: 0, tuesday: 1, wednesday: 2, thursday: 3, friday: 4, saturday: 5, sunday: 6 };
const startDate = "2022-06-02";
const endDate = "2022-06-20";
function daysindates(arr) {
    let stdate = startDate.substr(-2);
    let endate = endDate.substr(-2);
    let myarr = [],
        result = [],
        finalresult = [];
    for (y of arr) {
        for (let i = parseInt(stdate) + days[y]; i <= parseInt(endate); i += 7) {
            result.push(i);
        }
    }
    finalresult = result.map((item) => {
        return "2022-06-" + item;
    });
    console.log(finalresult);
}

daysindates(["monday", "tuesday"]);
Run Code Online (Sandbox Code Playgroud)