Search code examples
javascriptdatetimegoogle-apps-scriptgoogle-sheetsweak-typing

Trying to add to dateTime in sheets


function getFirstEmptyRow() {
  var spr = SpreadsheetApp.getActiveSpreadsheet();
  var column = spr.getRange('A:A');
  var values = column.getValues(); // get all data in one call
  var ct = 0;
  while ( values[ct][0] != "" ) {
    ct++;
  }
  return (ct);
}

function getLatestTime() {
  return SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange(getFirstEmptyRow(),1).getValue();
}

function getLatestPoints() {
  return SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange(getFirstEmptyRow(),2).getValue();
}

function getLatestAverage() {
  return SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange(getFirstEmptyRow(),3).getValue();
}

function daysLeft(){
  var pointsLeft = 24250 - getLatestPoints();
  return  (pointsLeft / getLatestAverage()) / 24;
}

function nextRedeem() { //Problem is with this function:
  var redeemTime = getLatestTime() + daysLeft() + (2/24); 
  return redeemTime;
}

In my sheet I have a list of rows with 1)a date/time 2)a point value and 3)A running average of points per hour. I am trying to write a function that figures out how much time is left before the points reach a certain number and add it to the latest time to figure out at what time I expect to have that number of points.

I have little experience with java script and weak typing. My problem is that when I try to add a number to my returned date value I either get a string or just NaN. My other problem is that sheets seems to interpret dates into a number differently than Number() does.

If my nextRedeem() function simply returns getLatestTime(), I can get sheets to show it either as a date or the number of days since 1/1/1900 or whatever it is. At that point, in a cell I can add to it. I can add getLatestTime() and daysLeft() in a cell and it works fine. I can also add the timezone offset and it works, in a cell. But when I do it in this function nothing seems to work. I have tried adding .value to the function calls and using parseFloat() but that gives me NaN.

How do I do arithmetic with these function returns?


Solution

  • So Date.parse gets me half way there, but it give me milliseconds since 1/1/1970, where google is days since 12/30/1899. So I just had to use some math which I left uncomputed for clarity.

    function dateToNum(date) {
      return (Date.parse(date)/1000/60/60/24 + 25569)
    }
    

    Now I can use dateToNum(getLatestTime()) and do whatever math I want to it. When this number is put into a cell that is formatted to datetime it will display correctly.