title: Calculate time duration with google script
body: <p>I'm new to coding and I found a script that I slightly adapted for my purpose: record on a timesheet the timestamps of the beginning and the end of an action, when you press buttons "Begin" and "End". I would also like the script to calculate the time duration between the two timestamps, which at first I thought would be easy but I'm unable to find a solution, so I'm asking for your help.</p>
  
  <pre><code>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());
  }
  </code></pre>
  
  <p>Thanks everybody, I wrote a new version of my script after reading your suggestions. But I get a #NUM! error in column C.</p>
  
  <pre><code>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))
  }
  </code></pre>