记录单元格值时间



我试图找到记录单元格具有特定值的时间量。示例:如果 H4 = ABC,然后更改为 XYZ;我需要记录单元格 H4 在更改为 XYZ 之前为 ABC 的时间量。我无法在谷歌脚本库中找到计时器函数。任何帮助将不胜感激。这是工作表和当前运行的所有脚本的链接。https://docs.google.com/spreadsheets/d/1eqOXVR9_2fe246PejvwUZd-Z1RoDN8OyS9B7Hk8FZRI/edit?usp=sharing

我也不知道 GAS 中的计时器函数,无论如何让它一直运行并不是最佳选择。更好的方法似乎是计算您拥有的时间戳与当前日期之间的单元格更改的时差。

我对这个函数进行了一些调整,使其还包括小时差异:

function dateDiff(start, end) {
  var diff = { years: 0, months: 0, days: 0 };
  var timeDiff = end - start;
  if (timeDiff > 0) {
    diff.years = end.getFullYear() - start.getFullYear();
    diff.months = end.getMonth() - start.getMonth();
    diff.days = end.getDate() - start.getDate();
    diff.hours = end.getHours() - start.getHours();
    if (diff.months < 0) {
      diff.years--;
      diff.months += 12;
    }
    if (diff.days < 0) {
      diff.months = Math.max(0, diff.months - 1);
      diff.days += 30;
    }
    if (diff.hours < 0) {
      diff.days = Math.max(0, diff.days - 1);
      diff.hours += 24;
    }
  }
  return diff;
};

而你的onEdit函数现在使用此 dateDiff 函数:

function onEdit() {
  // This section returns if you're not on the SBC/HP spreadsheet.
  var sheet = "SBC/HP";
  var s = SpreadsheetApp.getActiveSheet();
  var r = s.getActiveCell();
  // if r is in column h { do the rest }
  if( r.getColumn() != 11){
    var row = r.getRow();
    var previousDate = new Date(s.getRange(row, 11).getValue()); //getting the timestamp of the previous change. Looks like the year should be YYYY, not YY as it is now
    var time = new Date();
    var timeDiff = dateDiff(previousDate, time); //calculating time difference in a separate function
    time = Utilities.formatDate(time, "GMT-05:00", "MM/dd/yy, hh:mm:ss");
    s.getRange(row, 12).setValue(timeDiff.years + ' years ' + timeDiff.months + ' months ' + timeDiff.days + ' days ' + timeDiff.hours + ' hours'); //pasting time difference in some format in a separate cell
    s.getRange('K' + row.toString()).setValue(time);
  }
}

您可以在此处查看其工作原理

将 Stackdriver Logging 与 onEdit() 结合使用。然后使用日志筛选器和/或日志导出来提取 INFO 日志的时间戳。

function onEdit (e) {
  var message = e.range.getA1Notation() + " changed to " + e.value;
  console.info({message:message});
}

在脚本编辑器中转到该项目日志查看器View > Stackdriver Logging。从这里,您可以过滤掉 console.info() 消息,并获取与堆栈驱动程序日志记录消息中包含相同e.range.getA1Notation()的时间戳的时差。

堆栈驱动程序文档

最新更新