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

如何在Apps Script中编写函数获取指定月份的所有日期数组

Google Apps Script 获取指定日期所在月全部日期实现

直接封装可复用函数,传入任意合法日期对象,即可返回当月所有日期组成的数组,日期格式统一为YYYY-MM-DD。

函数代码

function getDatesInMonth(inputDate) {
  const targetDate = new Date(inputDate);
  const year = targetDate.getFullYear();
  const month = targetDate.getMonth();
  const dateList = [];

  // 从当月1号开始遍历
  let current = new Date(year, month, 1);
  while (current.getMonth() === month) {
    // 格式化补零
    const formatMonth = String(current.getMonth() + 1).padStart(2, '0');
    const formatDay = String(current.getDate()).padStart(2, '0');
    dateList.push(`${current.getFullYear()}-${formatMonth}-${formatDay}`);
    // 日期向后推1天
    current.setDate(current.getDate() + 1);
  }
  return dateList;
}

使用示例

传入2022年4月的任意日期调用:

// 示例:传入2022年4月任意一天,比如4月5日
const aprilDates = getDatesInMonth(new Date(2022, 3, 5));

返回结果为当月所有日期的集合:
["2022-04-01", "2022-04-02", "2022-04-03", ... , "2022-04-30"]

特性说明

  • 自动适配不同月份天数,无需手动判断大小月、2月闰年情况
  • 所有日期自动补前导零,符合标准日期格式
  • 不会修改传入的原始日期对象,无副作用
  • 兼容所有合法Date入参,包括日期字符串转成的Date对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 20:45:51