Miu
Miu

Reputation: 844

Google Calendar event created at a wrong date and time

.createEvent() doesn't work properly

When I executed the following code, an event was created at the wrong date and time. I wanted to create an event on 2021/2/21 17:00 - 22:00, but the event was created on 2021/2/22 7:00 - 12:00.
Here are my GAS code and a screenshot of my Google Calendar.

function pracCalendar() {
  const id = '[email protected]';
  const calendar = CalendarApp.getCalendarById(id);

  const title = 'Test Event';
  const startTime = new Date('2021/2/21 17:00');
  const endTime = new Date('2021/2/21 22:00');
  const options = {
    description: 'Test Description',
    location: 'Test Location',
    guests: '[email protected]',
    sendInvites: true
  }

  calendar.createEvent(title, startTime, endTime, options);
}

Google Calendar


Is this caused by timezone?

I'm not sure if it's related but just in case... I currently live in Japan. My Google Calendar's timezone is Asia/Tokyo.

Could anyone tell me how to solve the problem?

Upvotes: 1

Views: 1382

Answers (1)

Marios
Marios

Reputation: 27350

Possible Issue:

I think the issue has to do with the different timezone between the Google Apps Script project and your calendar.

To check that, please add to your current script the following two lines:

  console.log(Session.getScriptTimeZone()) // script timezone
  console.log(CalendarApp.getTimeZone()) // calendar timezone

Solution:

If there is a discrepancy between the two timezones, update the timezone of the Google Apps Script project. You need to open the appsscript.json file and adjust the timezone to match exactly the timezone of your calendar.

Here you can find the instructions on how to open the appsscript.json file:

after you unhide it, it will be visible in the script editor. For example, you need to change Europe/Paris from:

"timeZone": "Europe/Paris",

to what CalendarApp.getTimeZone() returns (most likely Asia/Tokyo) and save the changes.

Please Note:

Besides the 2 hours difference, your code should create an event for the 21st of February (2021/2/21) but the resulting event (in your screenshot) is created on 22nd. Be careful with this.

Upvotes: 2

Related Questions