My Google Sheets spreadsheet has a list of appointments that I am trying to compare with tomorrow's date (so that I can send a reminder the day before). My current code is returning true on certain dates that aren't on the spreadsheet. We have no appointments on Sundays and I am currently testing this on a Saturday but still receiving some true values. I searched the spreadsheet thoroughly for a possible booking mistake but there are none. I did notice, however, that when it looks for the date 4:24:2016 (which is tomorrow) it will return true on 4:14:2016 dates. I am pretty much stumped at this point.
function myFunction() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var apptDates = sheet.getRange(2, 32, sheet.getLastRow() - 1, 1).getValues();
for (var i = 0; i <= apptDates.length; i++) {
var apptDate = new Date(apptDates[i][0]);
apptDate = apptDate.addHours(74);
function dayAway(date, day) {
return new Date(date.getTime() + day * (24 * 3600 * 1000));
}
Logger.log(apptDate >= dayAway(new Date(), 1));
}
}
When you use new Date()
you get a full JS Date object with not only day, month and year but also hours minutes, seconds and milliseconds .
That's why your comparison could not give results. Simply set the unneeded values to 0
and it will work. I used getTime()
to compare milliseconds but could have used toString()
as well, only the date objects are not suitable to check equality.
The Logger is a great help to debug such things.
code :
function myFunction() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var apptDates = sheet.getRange(2,6, sheet.getLastRow() - 1, 1).getValues();
for (var i = 0; i < apptDates.length; i++) {
var apptDate = new Date(apptDates[i][0]);
Logger.log(apptDate.getTime()+' ==? '+dayAway(new Date(new Date().setHours(0,0,0,0)), 1).getTime());
Logger.log(apptDate.getTime() == dayAway(new Date(new Date().setHours(0,0,0,0)), 1).getTime());
}
}
function dayAway(date, day) {
return new Date(date.getTime() + day * 24 * 3600 * 1000);
}
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.