1

I have a google sheet with rows that have some date values and other info to place on a gCal.

Date
9/4/2019
9/6/2019
9/5/2019

I am trying to run a loop that will only pull dates that are equal to a futureDate (which is today plus three days, currently 09/05/2019)

If I use the <= or => it works fine. Pulls the correct dates and places them on my calendar. I can't get the equal to futureDate to work. I have spent hours thinking it has something to do with the date format but then the <= should not work either. What am I missing here??

var today = new Date();
var futureDate = new Date();
futureDate.setDate(today.getDate()+3);

for(var i = 0; i<data.length; i++){

    if(data[i][11] == futureDate) {
      cal.createEvent(data[i][0], data[i][1], data[i][2], {location: data[i][3], description: data[i][10]}).setColor(data[i][5]);

//This one works and returns all dates that are not equal to futureDate
if(data[i][11] <= futureDate) {
      cal.createEvent(data[i][0], data[i][1], data[i][2], {location: data[i][3], description: data[i][10]}).setColor(data[i][5]);

I need only 09/05/2019 to return currently because today is 09/02/2019. (today + 3 days)

TheMaster
  • 45,448
  • 6
  • 62
  • 85
  • Because the comparative operators coerce Date objects to a number (their time value) but `==` (and `===`) do not. So on the one hand you're comparing primitives (numbers), on the other objects. So coerce the dates to number before using equality operators, e.g. `+data[i][11] == +futureDate` or more explicitly use *getTime* `data[i][11].getTime() == futureDate.getTime()`. – RobG Sep 02 '19 at 22:45
  • This worked perfectly. Thanks – Jimmy Signature Sep 02 '19 at 23:06

1 Answers1

0

This may be because of the hours and minutes in new Date().

I don't know the format of the dates in data[i][11]. But I set up A1 on my sheet =today()+3.

And I compared that value to futuredate from your script:

var today = new Date();
var futureDate = new Date();
futureDate.setDate(today.getDate()+3);

And the log shows this:

Script value: Thu Sep 05 17:03:10 GMT+00:00 2019

Sheet value: Thu Sep 05 00:00:00 GMT+00:00 2019


Edit

The fix:

  var today = new Date();
  var futureDate = new Date();
  futureDate.setDate(today.getDate()+3);
  futureDate.setHours(0,0,0,0);
ADW
  • 4,177
  • 1
  • 14
  • 22
  • I see your point, So how do I convert futureDate to have no "time"?? When I run the debug it does show both objects as 'dates' and you are right on with your log from above. – Jimmy Signature Sep 02 '19 at 18:12
  • @JimmySignature—use `today.setHours(0,0,0,0)`. You can do `var today = new Date(); var futureDate = new Date(today.setHours(0,0,0,0))` to set the time to 0 and copy it in one go. – RobG Sep 02 '19 at 22:50
  • Sorry I should have suggested a fix. Have done so now in an edit to the post. As RoG suggested, `setHours()` works nicely. Another way would be to turn it to milliseconds using `getTime()` and then round-down to the start of day. – ADW Sep 03 '19 at 03:48