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

如何修改getAllDaysInMonth函数以获取指定年份全年所有日期?

获取指定年份全年所有日期的解决方案

你可以基于现有的getAllDaysInMonth函数,封装一个新函数遍历全年12个月份(注意JavaScript的Date对象中月份是0起始的:1月对应0,12月对应11),把每个月的日期数组合并成一个全年的日期集合。

修改后的完整代码

function getAllDaysInMonth(year, month) {
    const date = new Date(year, month, 1);
    const dates = [];
    while (date.getMonth() === month) {
        dates.push(new Date(date));
        date.setDate(date.getDate() + 1);
    }
    return dates;
}

function getAllDaysInYear(year) {
    let allDays = [];
    // 循环0到11,覆盖全年12个月份
    for (let month = 0; month < 12; month++) {
        const monthDays = getAllDaysInMonth(year, month);
        allDays = [...allDays, ...monthDays];
        // 也可以用concat方法:allDays = allDays.concat(monthDays);
    }
    return allDays;
}

用法示例

// 获取2024年全年所有日期
const year2024Days = getAllDaysInYear(2024);
// 输出2024年1月1日
console.log(year2024Days[0]);
// 输出2024年12月31日
console.log(year2024Days[year2024Days.length - 1]);

补充说明

  • 原函数getAllDaysInMonth返回的是Date对象数组,每个元素都是对应日期的副本,避免了后续修改原对象导致的日期错乱问题
  • 新函数getAllDaysInYear通过12次循环调用原函数,将每个月的日期数组合并,最终返回全年的日期集合,完全适配你做日历式里程追踪的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 12:24:24