2017-10-28 50 views

回答

0

我不知道GAS中的定時器功能,無論如何,它不會是最佳的讓它一直運行。更好的方法似乎是計算您擁有的時間戳與當前日期之間的單元格更改時間差。

我已經調整了this function了一點,所以它也包括時間差:

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); 
    } 
} 

您可以檢查它如何作品here

+0

a-change,對不起,回來這麼晚,但這個工作得很好。我只對時間格式進行了一些更改,只包括日,小時和分鐘。 –

0

聯合Stackdriver LoggingonEdit()。然後使用Log Filters和/或Log Exporting來提取INFO日誌的時間戳。

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

    console.info({message:message}); 
} 

獲取對項目的腳本編輯器Log ViewerView > Stackdriver Logging。從這裏您可以篩選出console.info()消息,並從包含Stackdriver Logging消息中的相同e.range.getA1Notation()的時間戳中獲取時間差。

Stackdriver Docs

相關問題