You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取arrayStart与arrayEnd数组对应下标元素之间的所有日期

解决方法

核心实现思路

  • 先保证arrayStart和arrayEnd长度对齐,两个数组相同下标为一对匹配的起止日期
  • 遍历下标依次取出每对日期,转为moment实例后传入日期区间生成函数
  • 汇总所有区间的日期,同步生成你需要的日期配置对象

现有代码问题说明

你当前的代码存在几个明显的逻辑错误:

  • 给setStartDate、setEndDate传值时用了forEach,forEach没有返回值,会导致state赋值为undefined
  • 你定义的start、end函数仅做打印操作,没有返回日期值,调用getDaysBetweenDates时传入的是函数而非日期参数,运行会直接报错
  • getDaysBetweenDates内部每新增一个日期就遍历整个dates数组更新配置对象,存在大量无意义的重复操作

修正后完整实现代码

try {
    let res = await axios.get(`https://myseenapp.herokuapp.com/constructionSite/${_id}`);
    let data = res.data;
    setConstruction(data);

    // 先处理得到去重后的起止日期数组
    const tempStart = []
    const tempEnd = []
    data.forEach(e => {
        const convertStart = e.startDate.split('-').reverse().join('-')
        if (!tempStart.includes(convertStart)) {
            tempStart.push(convertStart)
        }
        const convertEnd = e.endDate.split('-').reverse().join('-')
        if (!tempEnd.includes(convertEnd)) {
            tempEnd.push(convertEnd)
        }
    })
    setStartDate(tempStart)
    setEndDate(tempEnd)

    // 单个日期间隔生成函数
    const getDaysBetweenDates = (startMoment, endMoment) => {
        const dates = []
        let now = startMoment.clone()
        while (now.isSameOrBefore(endMoment)) {
            const dateStr = now.format("YYYY-MM-DD")
            dates.push(dateStr)
            // 新增日期时直接赋值配置,无需重复遍历
            newDaysObject[dateStr] = {
                textColor: "white",
                color: 'gold',
                selected: true,
            }
            now.add(1, 'days')
        }
        return dates
    }

    // 遍历所有起止日期对,汇总所有日期
    const allDateList = []
    // 取最小长度避免下标越界
    const pairCount = Math.min(tempStart.length, tempEnd.length)
    for (let i = 0; i < pairCount; i++) {
        const startM = moment(tempStart[i])
        const endM = moment(tempEnd[i])
        const currentRangeDates = getDaysBetweenDates(startM, endM)
        allDateList.push(...currentRangeDates)
    }

    console.log('所有区间的日期汇总:', allDateList)
} catch (err) {
    console.log(err)
}

内容的提问来源于stack exchange,提问作者manon_ab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 05:39:01