skip to Main Content

I’m currently working on a Google Apps Script that automatically creates events in Google Calendar based on data from a Google Sheets document. The script executes successfully, and events are created, but the event times are incorrect, despite the correct time values being input in Google Sheets.

Issue
For instance, in the data, I request an event to be created at 8:00 AM, but when the event is created, it shows up as 8:52 AM in the calendar. The event time seems shifted by 52 minutes.

Here is the script I’ve used so far:

function createCalendarEvent() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var calendarId = '[email protected]'; // Replace with your actual calendar ID
  var calendar = CalendarApp.getCalendarById(calendarId);

  // Check if the calendar was retrieved successfully
  if (!calendar) {
    Logger.log("Calendar not found. Please check the calendar ID.");
    return;
  }

  // Get the data from the specified range
  var dataRange = sheet.getRange("P2:U" + sheet.getLastRow());
  var rows = dataRange.getValues();

  for (var i = 0; i < rows.length; i++) {
    var eventName = rows[i][0]; // Column P: Event Name
    var eventDate = new Date(rows[i][1]); // Column Q: Date
    var startTime = rows[i][2]; // Column R: Start Time
    var endTime = rows[i][3]; // Column S: End Time
    var description = rows[i][4]; // Column T: Description
    var location = rows[i][5]; // Column U: Location (optional)

    if (isNaN(eventDate.getTime())) {
      Logger.log('Invalid date on row ' + (i + 2));
      continue;
    }

    if (startTime && endTime) {
      var startDateTime = new Date(eventDate);
      startDateTime.setHours(Math.floor(startTime * 24), (startTime * 24 * 60) % 60);

      var endDateTime = new Date(eventDate);
      endDateTime.setHours(Math.floor(endTime * 24), (endTime * 24 * 60) % 60);

      // Create the event in Google Calendar
      calendar.createEvent(eventName, startDateTime, endDateTime, {
        description: description,
        location: location
      });

      Logger.log('Event created: ' + eventName + ', Start: ' + startDateTime + ', End: ' + endDateTime);
    } else {
      Logger.log('Invalid time on row ' + (i + 2));
    }
  }
}

What I’ve Tried:

  1. Checked the Calendar Object: Verified that the calendar is correctly fetched using getCalendarById(). The event is successfully created, so the calendar is being accessed.

  2. Date Formatting: Verified that the date format in Google Sheets is correct. The =ISDATE() formula confirms that the date column is valid.

  3. Time Formatting: Used the =ISNUMBER() formula to check the start and end times. It returns TRUE, confirming the time is valid.

  4. Combining Time with Date: For both start and end times, I used setHours() to combine the time values with the event date. Despite this, the event appears with an incorrect time shift (usually around 52 minutes later than expected).

Question:

  • How can I ensure that the time read from the sheet and set in the calendar matches the exact time in Google Sheets?
  • Is there a better way to handle time values from Google Sheets that might prevent this 52-minute shift?

Any help is greatly appreciated!

2

Answers


  1. Try this:

          const startDateTime = new Date(eventDate.getTime() + startTime.getTime());
          const endDateTime = new Date(eventDate.getTime() + endTime.getTime());
    

    Also, comment out the two Date.setHours() calls.

    See Working with date and time values in Google Sheets and Working with Dates and Times in Apps Script.

    Login or Signup to reply.
  2. Calendar Create Event with Exact Time

    I tested your code and refactored the script in a way that the sample data for both the Start and End times are in a 24-hour format. The basis I had for this is the statement Time Formatting: Used the =ISNUMBER() formula to check the start and end times. It returns TRUE, confirming the time is valid and to achieve the correct event output.

    Change:

      var startDateTime = new Date(eventDate);
      startDateTime.setHours(Math.floor(startTime * 24), (startTime * 24 * 60) % 60);
      var endDateTime = new Date(eventDate);
      endDateTime.setHours(Math.floor(endTime * 24), (endTime * 24 * 60) % 60);
    
      calendar.createEvent(eventName, startDateTime, endDateTime, {
        description: description,
        location: location
      });
    

    To:

      var startDateTime = new Date(eventDate).setHours(startTime.split(":")[0], startTime.split(":")[1]); // returns milliseconds
      var realStart = new Date(startDateTime) // converts milliseconds to new Date Object
      var endDateTime = new Date(eventDate).setHours(endTime.split(":")[0], endTime.split(":")[1]); // returns milliseconds
      var realEnd = new Date(endDateTime); // converts milliseconds to new Date Object
    
      calendar.createEvent(eventName, realStart, realEnd, {
        description: description,
        location: location
      });
    

    Sample Sheet:

    Sample Sheet

    Sample Output:

    Calendar Sample

    Full Refactored Code:

    function createCalendarEvent() {
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
      var calendarId = '[email protected]'; // Replace with your actual calendar ID
      var calendar = CalendarApp.getCalendarById(calendarId);
    
      if (!calendar) {
        Logger.log("Calendar not found. Please check the calendar ID.");
        return;
      }
    
      var dataRange = sheet.getRange("P2:U" + sheet.getLastRow());
      var rows = dataRange.getValues();
    
      for (var i = 0; i < rows.length; i++) {
        var eventName = rows[i][0];
        var eventDate = new Date(rows[i][1]);
        var startTime = rows[i][2];
        var endTime = rows[i][3];
        var description = rows[i][4];
        var location = rows[i][5];
    
        if (isNaN(eventDate.getTime())) {
          Logger.log('Invalid date on row ' + (i + 2));
          continue;
        }
    
        if (startTime && endTime) {
          var startDateTime = new Date(eventDate).setHours(startTime.split(":")[0], startTime.split(":")[1]);
          var realStart = new Date(startDateTime);
          var endDateTime = new Date(eventDate).setHours(endTime.split(":")[0], endTime.split(":")[1]);
          var realEnd = new Date(endDateTime);
    
          calendar.createEvent(eventName, realStart, realEnd, {
            description: description,
            location: location
          });
          
          Logger.log('Event created: ' + eventName + ', Start: ' + realStart + ', End: ' + realEnd);
        } else {
          Logger.log('Invalid time on row ' + (i + 2));
        }
      }
    }
    

    Reference:

    Split()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search