Add an Event to Google Calendar with JavaScript

I've been building a new events platform lately. I implemented something earlier today (and expected it to be more work than it was): the ability to add an event to Google Calendar.

Google Calendar is one of the most widely used calendar applications, and it made perfect sense to integrate it into our platform.

Our solution uses Google Calendar's URL parameters to create events. Here's how it works:

  • We generate a special URL that includes all the event details (name, description, start time, end time, and location).
  • When a user clicks to add an event to their Google Calendar, we open this URL in a new tab.
  • Google Calendar opens with a pre-filled event creation form, allowing users to review and save the event with just a few clicks.

Here's a simplified version of the function we use to generate the Google Calendar URL:

const addToGoogleCalendar = (event) => {
  const { name, description, start_datetime, end_datetime, location } = event;
  
  const formatDate = (dateString) => new Date(dateString)
    .toISOString()
    .replace(/-|:|\.\d\d\d/g, "");
  
  const dates = `${formatDate(start_datetime)}/${formatDate(end_datetime)}`;
  
  const url = `https://www.google.com/calendar/render?action=TEMPLATE` +
    `&text=${encodeURIComponent(name)}` +
    `&dates=${dates}` +
    `&details=${encodeURIComponent(description)}` +
    `&location=${encodeURIComponent(location)}`;
  
  window.open(url, "_blank");
};

// Example event object:
// const event = {
//   name: "Team Meeting",
//   description: "Weekly team sync-up",
//   start_datetime: "2023-09-15T09:00:00-07:00",
//   end_datetime: "2023-09-15T10:00:00-07:00",
//   location: "Conference Room A"
// };
//
// Usage:
// addToGoogleCalendar(event);

This function takes an event object, formats the dates, and constructs a URL with all the necessary parameters. When called, it opens a new tab with the Google Calendar event creation page, pre-filled with the event details. The trickiest part is just getting the date formatting right.

Pretty handy, right?

GoogleJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.