簡體   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