【问题标题】:How to automatically add a timestamp in google spreadsheet如何在谷歌电子表格中自动添加时间戳
【发布时间】:2014-12-10 01:07:19
【问题描述】:

我的 Google 电子表格中有一张包含 5 个单元格的表格,前 3 个仅包含单词,而后 2 个包含时间,特别是时间戳。

cell 1 = data
cell 2 = data
cell 3 = data
cell 4 = time start
cell 5 = time ended

现在,我想要的是当单元格 1 提供数据时,时间戳将自动出现在单元格 4 中。当单元格 2 和单元格 3 提供数据时,时间戳将成为单元格 5 的新值。

我的朋友给我一个代码,应该粘贴在脚本编辑器中:

function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

for (var i = 0; i <= numRows - 1; i++) {
  var row = values[i];
  Logger.log(row);
 }
};

function onOpen() {
 var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
 var entries = [{
 name : "Read Data",
 functionName : "readRows"
}];
spreadsheet.addMenu("Script Center Menu", entries);
};
function timestamp() {
return new Date()
}

并且此代码粘贴在=IF(B6="","",timestamp(B6))cell 4 中,而此=IF(D6="","",timestamp(C6&amp;B6)) 位于单元格5 中。在他的示例跟踪器中它的工作。但是当我将它复制到我的时,单元格 4 和单元格 5 中的输出是今天的日期而不是时间。

谁能帮助我?为什么输出的是日期而不是时间?

【问题讨论】:

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


【解决方案1】:

如果有帮助,您可以参考此tutorial。 在脚本代码中,更改

var timestamp_format = "MM-dd-yyyy"; // Timestamp Format.

var timestamp_format = "MM-dd-yyyy hh:mm:ss"; // Timestamp Format.

这应该会对你有所帮助。

【讨论】:

  • @PaulG - 即使没有链接,答案仍然包含一些答案。
  • @PaulG 你是对的,但我不想把功劳归功于花费时间和精力来记录和编码这些东西的原始开发人员。所以在这里,我只是为提问者提供正确的方向。当然,有时链接可能不起作用,在这种情况下,应该有人再次提问/回答问题。
【解决方案2】:

刚好遇到这个问题,修改了Internet Geeks提供的代码。

他们的代码通过更新指定的列来工作,时间戳被插入到另一个指定列的同一行中。

我改变的是我把日期和时间分开了,因为时间戳是一个字符串,不是日期格式。我的方式对于生成图表很有用。

它的工作原理是指定要跟踪更改的列,然后分别为日期和时间创建 upDate 和 upTime 列。

function onEdit(event) {
  var timezone = "GMT+1";
  var date_format = "MM/dd/yyyy";
  var time_format = "hh:mm";

  var updateColName = "Резултат";

  var DateColName = "upDate";
  var TimeColName = "upTime";

  var sheet = event.source.getActiveSheet(); // All sheets
  // var sheet = event.source.getSheetByName('Test'); //Name of the sheet where you want to run this script. 

  var actRng = event.source.getActiveRange();
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();

  var dateCol = headers[0].indexOf(DateColName);
  var timeCol = headers[0].indexOf(TimeColName);

  var updateCol = headers[0].indexOf(updateColName);
  updateCol = updateCol + 1;

  if (dateCol > -1 && timeCol > -1 && index > 1 && editColumn == updateCol) {
    // only timestamp if 'Last Updated' header exists, but not in the header row itself! 

    var cellDate = sheet.getRange(index, dateCol + 1);
    var cellTime = sheet.getRange(index, timeCol + 1);

    var date = Utilities.formatDate(new Date(), timezone, date_format);
    var time = Utilities.formatDate(new Date(), timezone, time_format);

    cellDate.setValue(date);
    cellTime.setValue(time);
  }
}

希望这对人们有所帮助。

更新和更简单的代码

function onEdit(e) {
  var sh = e.source.getActiveSheet();
  var sheets = ['Sheet1']; // Which sheets to run the code.

  // Columns with the data to be tracked. 1 = A, 2 = B...
  var ind = [1, 2, 3].indexOf(e.range.columnStart); 

  // Which columns to have the timestamp, related to the data cells.
  // Data in 1 (A) will have the timestamp in 4 (D)
  var stampCols = [4, 5, 6]

  if(sheets.indexOf(sh.getName()) == -1 || ind == -1) return;

  // Insert/Update the timestamp.
  var timestampCell = sh.getRange(e.range.rowStart, stampCols[ind]);
  timestampCell.setValue(typeof e.value == 'object' ? null : new Date());
}

【讨论】:

    【解决方案3】:

    我做了一个稍微不同的版本,也是基于Internet Geeks的代码

    为了支持多个命名工作表,并且由于 Google Sheets Script 目前不支持 Array.prototype.includes(),我包含了提到的 polyfill here

    另外,在我的版本中,时间戳标记的是该行单元格的创建日期,而不是此处提供的其他脚本中的上次更新日期。

    function onEdit(event) {
      var sheetNames = [
        'Pounds £', 
        'Euros €'
      ]
      var sheet = event.source.getActiveSheet();
      if (sheetNames.includes(sheet.getName())){
        var timezone = "GMT";
        var dateFormat = "MM/dd/yyyy";
        var updateColName = "Paid for ...";
        var dateColName = "Date";
    
        var actRng = sheet.getActiveRange();
        var editColumn = actRng.getColumn();
        var rowIndex = actRng.getRowIndex();
        var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
        var dateCol = headers[0].indexOf(dateColName) + 1;
        var updateCol = headers[0].indexOf(updateColName) + 1;
        var dateCell = sheet.getRange(rowIndex, dateCol);
        if (dateCol > 0 && rowIndex > 1 && editColumn == updateCol && dateCell.isBlank())
        {
          dateCell.setValue(Utilities.formatDate(new Date(), timezone, dateFormat));
        }
      }
    }
    
    // https://stackoverflow.com/a/51774307/349169
    // https://tc39.github.io/ecma262/#sec-array.prototype.includes
    if (!Array.prototype.includes) {
      Object.defineProperty(Array.prototype, 'includes', {
        value: function(searchElement, fromIndex) {
    
          if (this == null) {
            throw new TypeError('"this" is null or not defined');
          }
    
          // 1. Let O be ? ToObject(this value).
          var o = Object(this);
    
          // 2. Let len be ? ToLength(? Get(O, "length")).
          var len = o.length >>> 0;
    
          // 3. If len is 0, return false.
          if (len === 0) {
            return false;
          }
    
          // 4. Let n be ? ToInteger(fromIndex).
          //    (If fromIndex is undefined, this step produces the value 0.)
          var n = fromIndex | 0;
    
          // 5. If n ≥ 0, then
          //  a. Let k be n.
          // 6. Else n < 0,
          //  a. Let k be len + n.
          //  b. If k < 0, let k be 0.
          var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
    
          function sameValueZero(x, y) {
            return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
          }
    
          // 7. Repeat, while k < len
          while (k < len) {
            // a. Let elementK be the result of ? Get(O, ! ToString(k)).
            // b. If SameValueZero(searchElement, elementK) is true, return true.
            if (sameValueZero(o[k], searchElement)) {
              return true;
            }
            // c. Increase k by 1. 
            k++;
          }
    
          // 8. Return false
          return false;
        }
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多