Search code examples
javascriptdatetimegoogle-apps-scriptgoogle-calendar-api

How to create All Day Calendar Event 14 days from now


I'm trying to create an all-day calendar event to 14 days from today using Google App Script but I keep getting the error

Exception: The parameters (String,String) don't match the method signature for CalendarApp.Calendar.createAllDayEvent.

My script is:

  var SheetApp = SpreadsheetApp.getActiveSheet();  
  var SelectedRow = SheetApp.getActiveRange().getRowIndex();
  var value = SheetApp.getRange(SelectedRow, 8).getValue(); //Name of the event

  var eventCal = CalendarApp.getCalendarById("sampleemail@gmail.com");
  eventCal.createAllDayEvent(value.toString(), new Date() + 14);

Solution

  • When you add a number to a Date object, the Date is automatically converted to its underlying value, i.e., the number of milliseconds since the epoch. The result of the addition will be that number of milliseconds plus 14, which is just a big integer. The createAllDayEvent() method expects a Date object rather than an integer.

    To get a date that is 14 days from now, use Date.setDate(). This method has the benefit that it automatically takes care of rolling into the next month or next year as necessary, but be careful. The setDate() method modifies a Date object in place, but does not return the Date object. Instead, it returns the underlying value, i.e., the number of milliseconds since the epoch.

    This means that you cannot just assign the result you get from setDate() to a variable in the hope of getting a valid Date. Something like const twoWeeksFromNow = new Date().setDate(new Date().getDate() + 14) will not work if you expect twoWeeksFromNow to contain a Date.

    An easy way to get it right is to use a short utility function, like this:

    function testCreateAllDayEvent() {
      const twoWeeksFromNow = dateOffset_(new Date(), +14);
      const eventCal = CalendarApp.getCalendarById("sample_email@gmail.com");
      const sheet = SpreadsheetApp.getActiveSheet();
      const eventTitle = sheet
        .getRange('H' + sheet.getActiveRange().getRow())
        .getDisplayValue();
      eventCal.createAllDayEvent(eventTitle, twoWeeksFromNow);
    }
    
    /**
    * Gets a new Date object that is offset by numDays from date.
    *
    * @param {Date} date The date from which to count.
    * @param {Number} numDays The number of days to add or subtract from date.
    * @return {Date} A new Date object that is offset by numDays from date.
    */
    function dateOffset_(date, numDays) {
      const newDate = new Date(date);
      newDate.setDate(date.getDate() + numDays);
      return newDate;
    }