尝试比较日期,getValues()将日期转换为字符串。无法比较

时间:2014-12-11 08:37:02

标签: date comparison google-sheets

使用Google表格和表单,我正在尝试设置一个简单的预订系统,我需要找到特定日期的匹配项并显示预订数据。我遇到的问题是,当我从电子表格中提取预订日期时,它们似乎被转换为字符串,因此我无法再轻松比较它们。

我的代码:

//The is the handler for the date-picker
function dateChange(eventInfo) {

var selectedDate = eventInfo.parameter.date_picker;
var bookingsSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var bookingsDatabase = SpreadsheetApp.openById("<ID IN HERE>");

//Get data for current event
var bookingsData = bookingsDatabase.getSheetByName('<SHEET>');

//Get data for selected date
var bookingsDatesList = bookingsData.getRange(2,2,bookingsData.getLastRow()).getValues();

//This pops up with 'Sat Dec 27 2014 03:00:00 GMT-0800 (PST) - Sat Dec 27 2014 03:00:00 GMT-0800 (PST)' - They echo the same, but they don't generate matches.
SpreadsheetApp.getUi().alert(bookingsDatesList[0] + " - " + selectedDate);

//This pops up with 'Sat Dec 27 2014 03:00:00 GMT-0800 (PST) - 1419678000000' - the date on the left doesn't seem to be a date object because it doesn't convert to an integer.
SpreadsheetApp.getUi().alert(bookingsDatesList[0].valueOf() + " - " + selectedDate.valueOf());

// Search for selected date among database entries
for(var n=0; n<bookingsDatesList.length-1; n++) {
  if(bookingsDatesList[n].valueOf() == selectedDate.valueOf()) {
      SpreadsheetApp.getUi().alert('match!');
  }
}

我唯一的选择是尝试将每个字符串重新转换回日期吗?或者我可以将日期选择器日期转换为字符串吗?或者它是选项3 - 我错过了一些非常明显的东西。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

好的,我已经使用我的上述启示来尝试不同的方法,使用getValue()而不是getValues(),它工作正常。更改了代码如下:

var bookingsDatesList = bookingsData.getRange(2,2,bookingsData.getLastRow());

// Search for selected date among database entries
for(var n=1; n<bookingsDatesList.getNumRows(); n++) {
  if(bookingsDatesList.getCell(n,1).getValue().valueOf() == selectedDate.valueOf()) {
      SpreadsheetApp.getUi().alert('match!');
  }
}

就像这样,匹配警报弹出就好了。非常奇怪,我必须使用单个&#39; getValue()&#39;命令而不是&#39; getValues()&#39;。