繁体   English   中英

在 Google Sheet Script Editor 中计算日期差异

[英]Calculating Date Difference in Google Sheet Script Editor

我正在尝试计算 today() - 在脚本编辑器中的过去日期

我在原始数据中已经有了所有这些日期

它们采用以下格式..

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

我试过这些代码进行计算

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

}

但我收到一条错误消息,说

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

我应该为这些计算做不同的格式吗?

可以以毫秒为单位将日期转换为时间戳纪元,以使其更容易。

通常在处理日期时,人们会使用moment库,可以在这里找到: https : //github.com/moment/moment 但是,如果这是一个简单的场景并且不会围绕日期编写大量代码,那么只需编写一个简单的脚本即可。

 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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