简体   繁体   中英

Calculating Date Difference in Google Sheet Script Editor

I am trying to calculate today() - past date in script editor

I have all these dates already in the raw data

They are in the below format..

10/31/2018 10/31/2018 11/8/2018 11/11/2018 11/18/2018 11/18/2018

I tried these codes for calculation

function getDate(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Lists')
  var data = sh.getRange('A:A').getValues(); // read all data in the sheet
  var sec=1000;
  var min=60*sec;
  var hour=60*min;
  var day=24*hour;
  var hd=new Date(data).valueOf();
  var td=new Date().valueOf();
  var diff=td-hd;
  var days=Math.floor(diff/day);
 // range.offset(rowOffset, columnOffset, numRows, numColumns)


  Logger.log('Day_Difference:',days);
  sh.getRange(1,1,data.length(),2).setValues(days); // write back to the sheet

}

but I get an error message saying,

TypeError: Cannot call property length in object Dates,Wed Oct 31 2018 00:00:00 GMT-0400 (EDT),Wed Oct 31 2018 

Should I do different formats for these calculation??

Can convert dates to timestamp epochs in milliseconds to make this easier.

Usually when doing a lot of work with dates folks use the moment library which can be found here: https://github.com/moment/moment . However if this is a simple scenario and a bulk of code is not to be written around dates would just do a simple script.

 const dates = [ '10/31/2018', '10/31/2018', '11/8/2018', '11/11/2018', '11/18/2018', '11/18/2018' ]; function dateDifference(a, b) { const aEpoch = +new Date(a); const bEpoch = +new Date(b); const maxEpoch = Math.max(aEpoch, bEpoch); const minEpoch = Math.min(aEpoch, bEpoch); return maxEpoch - minEpoch; } console.log(dateDifference(dates[0], dates[1])); // Expect 0 console.log(dateDifference(dates[1], dates[2])); // Expect 694800000 milliseconds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM