在Google工作表脚本中将时间戳转换为日期

时间:2018-10-11 04:38:08

标签: javascript datetime google-apps-script google-sheets

我正在编写一个针对带有日期的列的代码,我想获取日期并将其与当前日期进行比较,以便获得两者之间的差异。

我遇到了无法解决的问题。看来,当我在范围内使用.getValues时,它将每个时间戳记放置在一个数组中,然后将那些数组放置在另一个数组中。像这样:[[(new Date(1539619200000))],[(new Date(1540396800000))],[(new Date(1540828800000))]]

我只想将所有值放在1个数组中,所以我可以开始解决如何将时间戳转换为正常日期。我也是这个的初学者,如果这是一个基本问题,我感到抱歉。

function datesincolumn() //collects only the date values in range
{

 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets()[0];
 var lastRow = sheet.getLastRow(); //will identify last row with any data 
 entered
 var range = sheet.getRange('D2:D' + lastRow); //will get range of cells 
 with data present
 var dates = range.getValues();//gets all values in the range
 var CurrentDate = new Date();
 var timestamps = [];

 for (i = 0; i <= dates.length; i++)
 {
   if (dates[i] >= i)
   {
     timestamps.push(dates[i]);
   }

 }

  Logger.log(dates);

}

1 个答案:

答案 0 :(得分:0)

使用.getValues()时,您将总是获得二维数组。外部数组代表行,内部数组代表列。由于只获得一列,因此您可以简单地将[0]附加到dates[i]上。

function datesincolumn() { //collects only the date values in range  
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var lastRow = sheet.getLastRow(); //will identify last row with any data entered
  var range = sheet.getRange('D2:D' + lastRow); //will get range of cells with data present
  var dates = range.getValues();//gets all values in the range
  var CurrentDate = new Date();
  var timestamps = [];
  for (var i = 0; i <= dates.length; i++) {
    var date = dates[i][0];
    if (date >= i)
      timestamps.push(date);
  }
  Logger.log(dates);
}