2017-01-09 81 views
1

我是新來的編碼,我發現一個腳本,我稍微適應了我的目的:在時間表上記錄一個動作的開始和結束的時間戳,當您按下「開始「和」結束「。我還希望腳本計算兩個時間戳之間的時間間隔,起初我認爲這很容易,但我無法找到解決方案,所以我要求您的幫助。使用谷歌腳本計算時長

function setValue(cellname, value) { 
SpreadsheetApp.getActiveSpreadsheet().getRange(cellname).setValue(value); 
} 

function getValue(cellname, value) { 
return SpreadsheetApp.getActiveSpreadsheet().getRange(cellname).getValue(); 
} 

function getNextRow() { 
return SpreadsheetApp.getActiveSpreadsheet().getLastRow() + 1; 
} 
function getLastRow() { 
return SpreadsheetApp.getActiveSpreadsheet().getLastRow(); 
} 

function addRecord(a, b) { 
var row =getNextRow(); 
setValue('A' + row, a); 
setValue('B' + row, b); 

} 

function addRecord2(c) { 
var row =getLastRow(); 
setValue('C' + row, c); 
} 

function Begin() { 
addRecord(getValue('B1'), new Date()); 
} 
function End() { 
addRecord2(new Date()); 
} 

感謝大家,在閱讀您的建議後,我寫了一個新版本的腳本。但我得到#NUM!列C中錯誤

var start = 0; 
var finish = 0; 
function setValue(cellname, value) { 
SpreadsheetApp.getActiveSpreadsheet().getRange(cellname).setValue(value); 
} 

function getNextRow() { 
return SpreadsheetApp.getActiveSpreadsheet().getLastRow() + 1; 
} 
function getLastRow() { 
return SpreadsheetApp.getActiveSpreadsheet().getLastRow(); 
} 
function addRecord(a) { 
var row =getNextRow(); 
setValue('A' + row, a); 
} 
function addRecord2(b) { 
var row =getLastRow(); 
setValue('B' + row, b); 
} 
function addRecord3(c) { 
var row =getLastRow(); 
    setValue('C' + row, c); 
} 
function begin() { 
start=addRecord(new Date().getTime()); 
} 
function end() { 
finish=addRecord2(new Date().getTime()); 
    addRecord3((finish-start)) 
} 
+1

新日期()返回一個日期的對象。一個Date對象有一個getTime'方法,它返回毫秒數...從另一箇中減去一個以獲得以毫秒爲單位的差值。執行適當的計算以獲得年,月,日,小時,分鐘,秒所需的 –

+0

還有getHours(),getMinutes()等等。看到這個[日期/時間函數教程](http://javascript.info/tutorial/datetime-functions) –

+1

幾個問題:你是什麼意思**按下按鈕**?你有插入繪圖和分配的腳本給那些?如果是的話,那麼你自己分配了Begin()和End()函數嗎?另外,你想計算一個動作開始和結束的時間戳,哪個動作?分別按下開始和結束按鈕?而且,時差可以用各種格式來衡量。你到底在找什麼? –

回答

0
var start = 0; 
var finish = 0; 
var yourCell = SpreadsheetApp.getActiveSpreadsheet().getRange(cellname); 

function begin(){ 
    start = new Date().getTime(); 
} 

function end(){ 
    finish = new Date().getTime(); 
    writeElapsed(start, finish) 
} 

function writeElapsed(start, finish){ 
    yourCell.setValue(finish - start); //will give elapsed time in ms 
} 
+0

感謝Sam的回答。我將代碼的某些部分重寫爲我的,但出現錯誤。 – Marie

+0

@瑪麗你得到了什麼類型的錯誤?什麼不工作?請分享。 –