You need to enable JavaScript to run this app. Google Apps Script中如何获取运行当月天数以插入对应数量表格行
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script中如何获取运行当月天数以插入对应数量表格行

当月总天数计算与Sheets自动插行实现

当月总天数计算逻辑

Google Apps Script 基于 JavaScript Date 对象实现,无需手动计算两个日期间隔,可直接通过内置日期规则快速获取当月总天数:

  • 构造日期时,传入当前年、当前月的下一月、日期0,Date对象会自动回退到当前自然月的最后一天
  • 对该日期调用getDate()方法,返回的数值就是当月总天数,自动适配大小月、闰年场景
// 获取运行时的当前日期
const currentDate = new Date();
// 计算当月总天数
const daysOfCurrentMonth = new Date(
  currentDate.getFullYear(),
  currentDate.getMonth() + 1,
  0
).getDate();

结合insertRows的完整实现

使用Sheets API的insertRows(rowIndex, numRows)方法时,直接将计算得到的当月天数作为第二个参数传入即可。注意insertRows的行索引是1起始计数,需根据实际场景调整插入起始位置:

function addMonthlyRows() {
  // 获取当前活动工作表
  const activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  // 计算当月总天数
  const currentDate = new Date();
  const daysInMonth = new Date(
    currentDate.getFullYear(),
    currentDate.getMonth() + 1,
    0
  ).getDate();
  // 插入起始行:示例为第2行(假设第1行是表头),可按需修改
  const startRow = 2;
  // 执行插入行操作
  activeSheet.insertRows(startRow, daysInMonth);
}

注意事项

  • 若需替换原有固定行而非新增插入,可搭配deleteRows方法先清空旧行后再执行插入
  • 如需固定计算指定月份的天数,只需修改currentDate对应的年、月赋值即可,核心计算逻辑无需变动
  • 该方案完全依托Apps Script内置能力实现,无需额外引入日期计算工具,运行稳定高效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 14:54:04