Irad
Irad

Reputation: 3

Google Apps Script (Calendar) - Compare if 2 events are in the same day

I don't know JavaScript (I know a little Java) but I want to write a simple script that deletes my school classes events when there is a vacation event but it simply doesn't work... What is the problem?

function vacations()                                                 
{                                                    
  var school_calendar = CalendarApp.getCalendarsByName("Timetable")[0].getEvents(new Date("September 1, 2016"),new Date("June 20, 2017"));
  var vacations = CalendarApp.getCalendarsByName("Vacations")[0].getEvents(new Date("September 1, 2016"),new Date("June 20, 2017"));
  for (var i = 0; i < vacations.length; i++)
  {
    var vacation = vacations[i];
    for (var j = 0; j < school_calendar.length; j++) 
    {
      var school_class = school_calendar[j];
      if(vacation.getAllDayStartDate() == school_class.getStartTime())
      {
        school_class.deleteEvent();
      }
    }
  }
}

Upvotes: 0

Views: 597

Answers (1)

Jasper Duizendstra
Jasper Duizendstra

Reputation: 2617

Comparing a Date vacation.getAllDayStartDate()with a Date school_class.getStartTime() can work if you compare them like:

vacation.getAllDayStartDate().getTime() === school_class.getStartTime().getTime()

However, one contains a date with a time set at midnight:

getAllDayStartDate()

Gets the date on which this all-day calendar event begins. (If this is not an all-day event, then this method will throw an exception.) The returned Date will represent midnight at the beginning of the day on which the event starts in the script's time zone. To use the calendar's time zone instead, call getStartTime().

And the other contains a date and time:

getStartTime()

Gets the date and time at which this calendar event begins. For non–all-day events, this will be the instant in time at which the event was defined to start. For all-day events, which only store a start date (not a date and time), this will be midnight at the beginning of the day on which the event starts in the calendar's time zone. This allows meaningful comparison of start times for all types of events; however, it will not necessarily preserve the original day-of-year unmodified.

For all-day events, getAllDayStartDate() should almost always be called in preference to this method.

Make sure you compare the right formats, and use the debugger or Logger to see what is going in in the code.

Upvotes: 1

Related Questions