0
votes

I need help with some quick coding with google apps script, linking to my googlesheets spreadsheet.

In the googlespreadsheets, I have a cell with the value “26-Jun-2020”. It is a date. I want to use google apps script to calculate the number of days difference between that date (“26-Jun-2020”) and today’s day, but it won’t do the calculation for me somehow.

If I print only “expiry_date[i]” using Logger.log(expiry_date[i]), it will provide the output “Fri Dec 17 2021 01:00:00 GMT-0500 (Eastern Standard Time) “

function Put_Options_Expiry_Alert() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Long equity (sell puts)");
  //var timeZone = AdsApp.currentAccount().getTimeZone(); //Get timezone of current spreadsheet

  var status = sheet.getRange("F:F").getValues();
  var expiry_date = sheet.getRange("M:M").getValues();
  var potential_capitaloutlay_USD = sheet.getRange("Z:Z").getValues();

  Logger.log("Length of status = " + status.length);
  Logger.log("Length of expiry_date = " + expiry_date.length);
  Logger.log("Length of potential_capitaloutlay_USD = " + potential_capitaloutlay_USD.length);

  for (var i = 0; i < status.length; i++) {
    
    if (status[i] == "Entered") { //Evaluate if this is a live Put position
      
      //Calculate the time difference of two dates using date2. getTime() – date1. getTime();
      //Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (1000*60*60*24)
      Logger.log("expiry date is = "+expiry_date[i]);
      Logger.log("today's date is = "+Date());
      
      var days_to_expiry = dateDiffInDays(expiry_date[i],Date());
      Logger.log(days_to_expiry);

    }
  }

}

// Function that returns the number of days difference between DateA and DateB 
// DateA and DateB are javascript Date objects
function dateDiffInDays(DateA, DateB) {
  
  var milliseconds_per_day = 1000 * 24 * 60; // number of milliseconds in a day 
  const utcA = Date.UTC(2021, DateA.getMonth(), DateA.getDate());
  const utcB = Date.UTC(2020, DateB.getMonth(), DateB.getDate());

  return Math.floor((utc2 - utc1) / milliseconds_per_day);
}


1

1 Answers

1
votes
function timeDiffDays(Start, End) {
  var day = 86400000;
  var t1 = new Date(Start).valueOf();
  var t2 = new Date(End).valueOf();
  var d = t2 - t1;
  return Math.floor(d / day);
}