【问题标题】:Google script add row with date only on certain datesGoogle脚本仅在某些日期添加带有日期的行
【发布时间】:2020-09-30 11:13:54
【问题描述】:

我正在尝试制作一个 Google 表格,该表格会在相应日期前两天自动在第一列中添加带有工作日日期的新行(在星期六添加星期一,在星期日添加星期二等)。为此,我编写了以下函数:

function addRowsWithDate() {
  var ss = SpreadsheetApp.getActiveSheet();
  
  var Today = new Date();
  Today.setDate(Today.getDate()+0); // I am using this to experiment with different dates
  var newDate = new Date();
  var dayOfWeek = Today.getDay();
  
  if (dayOfWeek<=3 || dayOfWeek==6){ // On Saturday through Wednesday
    newDate.setDate(Today.getDate()+2);
    ss.insertRowsBefore(1, 1); // Add new rows
    ss.getRange(1, 1).setValue(newDate); // Set date to the day after tomorrow 
  }
}

如果我保留 +0 原样或注释掉该行,这将按预期工作,但是一旦我开始更改该值以试验在不同日期运行此代码时会发生什么,我将返回其他日期个月。例如,今天偏移到+3(截至 9 月 31 日)会添加一行与 9 月 5 日。现在我正在输入这个,我发现问题可能在于getDate() 返回月份中的某一天,而不是像我读到的here 那样返回星期几。那是对的吗?如果是这样,是否还有另一个函数可以在 Google 表格脚本中返回星期几?

编辑:这似乎是一些包装问题。当我设置 +3 时,它会返回 9 月 5 日而不是 10 月 5 日,如果我设置 -30,我会再次得到 10 月 3 日。

【问题讨论】:

  • 尝试使用 getDay() 函数获取日期,然后使用 if() 函数进行相应的递增。
  • @Harsh 我不关注。这不是我已经在做的吗?
  • 今天是星期三。如果您添加 +1,则为星期四。后者是一周的第四天。请记住,星期日为 0,因此星期四为 4。您的 if 条件将被跳过 +1 或 +2。
  • @Marios 是的,这就是我想要的样子。这个想法是我可以每天运行这个脚本,而无需在电子表格中添加周末。问题是当我设置 +3(假设是星期六)时,它返回 9 月 5 日而不是 10 月 5 日星期一。

标签: javascript google-apps-script google-sheets


【解决方案1】:

不要为newDate 创建new Date(),而是将newDate 定义为new Date(Today),然后在 if 循环中添加 2 天。

解决方案:

function addRowsWithDate() {
  var ss = SpreadsheetApp.getActiveSheet();
  
  var Today = new Date();
  Today.setDate(Today.getDate()+3); // I am using this to experiment with different dates
  var newDate = new Date(Today);
  var dayOfWeek = Today.getDay();
  
  
  if (dayOfWeek<=3 || dayOfWeek==6){ // On Saturday through Wednesday
    newDate.setDate(newDate.getDate()+2);
    ss.insertRowsBefore(1, 1); // Add new rows
    ss.getRange(1, 1).setValue(newDate); // Set date to the day after tomorrow 
    ss.getRange(1, 2).setValue(Today); 
  }
}

【讨论】:

  • 完美。谢谢。当我添加ss.getRange(1, 2).setValue(Today); 来打印假装今天的日期时,它返回与newDate 相同的日期。编辑newDate 时,这些更改是否也应用于Today
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
相关资源
最近更新 更多