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

如何在Google Scripts中获取以周日为起始的周首日或对应周数

问题原因

你触发报错是因为 SpreadsheetApp.Range.setValue() 方法仅接受1个入参,即需要写入单元格的内容,你同时传入了日期、时区、格式三个参数,不符合方法签名要求所以报错。日期格式或周数计算需要先处理完成后,再把最终值传给setValue。

解决方案

你可以按需选择下面两个需求的实现代码,替换原有报错的代码行即可:

方案1:写入当周周日(周起始为周日)到A2单元格

核心逻辑是利用JavaScript内置Date.getDay()方法计算本周首日日期:getDay()返回值0对应周日、1对应周一、...6对应周六,用当前日期减去当前星期对应的天数,即可得到本周周日的日期。

const today = new Date();
// 计算当周周日日期
const thisSunday = new Date(today.setDate(today.getDate() - today.getDay()));
// 写入单元格
new_sheet.getRange('A2').setValue(thisSunday);
// 可选:设置单元格日期显示格式,可自行修改格式规则
new_sheet.getRange('A2').setNumberFormat('yyyy-MM-dd');

方案2:写入以周日为起始的当前周数到A3单元格

直接复用你给工作表命名时的Utilities.formatDate方法,处理得到周数后传入即可:

// 按指定时区格式化得到周数
const weekNum = Utilities.formatDate(new Date(), 'GMT-7:00', 'w');
// 转数字后写入,不需要数字类型可直接传weekNum
new_sheet.getRange('A3').setValue(Number(weekNum));

完整修改后代码

function myFunction() {
  var ss        = SpreadsheetApp.getActiveSpreadsheet(); // 当前表格
  var old_sheet = ss.getActiveSheet();                   // 当前旧工作表
  var new_sheet = old_sheet.copyTo(ss);                  // 复制旧工作表
  SpreadsheetApp.flush()
  // 给新工作表命名逻辑保持不变
  new_sheet.setName(Utilities.formatDate(new Date(), 'GMT-7:00', 'w')); 
  
  // -------------- 按需保留需要的逻辑即可 --------------
  // 方案1逻辑:写入当周周日到A2
  const today = new Date();
  const thisSunday = new Date(today.setDate(today.getDate() - today.getDay()));
  new_sheet.getRange('A2').setValue(thisSunday);
  new_sheet.getRange('A2').setNumberFormat('yyyy-MM-dd');

  // 方案2逻辑:写入周数到A3
  const weekNum = Utilities.formatDate(new Date(), 'GMT-7:00', 'w');
  new_sheet.getRange('A3').setValue(Number(weekNum));
  // --------------------------------------------------

  new_sheet.getRange('B14:H18').clear({contentsOnly: true}); // 清空指定区域内容
  old_sheet.hideSheet(); // 隐藏旧工作表
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:45:07