Brutus
Brutus

Reputation: 163

How to set start and end time in event object for google calendar api

I am using google calendar api to create events on the calendar. I am following google's api document here https://developers.google.com/calendar/create-events#javascript.

var event = {
  'summary': 'Google I/O 2015',
  'location': '800 Howard St., San Francisco, CA 94103',
  'description': 'A chance to hear more about Google\'s developer products.',
  'start': {
    'dateTime': '2015-05-28T09:00:00-07:00',
    'timeZone': 'America/Los_Angeles'
  },
  'end': {
    'dateTime': '2015-05-28T17:00:00-07:00',
    'timeZone': 'America/Los_Angeles'
  },
  'attendees': [
    {'email': '[email protected]'},
    {'email': '[email protected]'}
  ],
};

My backed service is currently returning me the event start date and the time in this format 2020-06-10T10:00:00.000 and the duration in a string '01:30:00'. It also returning me the time zone America/Los_Angeles. How may I set my start datetime and end datetime using these values.

Upvotes: 2

Views: 2111

Answers (1)

ziganotschka
ziganotschka

Reputation: 26816

Requires a bit of playing with different Javascript date object methods

Sample:

  var timeString = "2020-06-10T10:00:00.000";
  var timeZone = "America/Los_Angeles";
  var duration = '01:30:00';

  var startDate = new Date(timeString);
  var msDuration = (Number(duration.split(':')[0]) * 60 * 60 + Number(duration.split(':')[1]) * 60  + Number(duration.split(':')[2])) * 1000;
  var endDate = new Date(startDate.getTime() + msDuration);
  var isoStartDate = new Date(startDate.getTime()-new Date().getTimezoneOffset()*60*1000).toISOString().split(".")[0];
  var isoEndDate = new Date(endDate.getTime()-(new Date().getTimezoneOffset())*60*1000).toISOString().split(".")[0];

  var event = {
    'summary': 'Google I/O 2015',
    'location': '800 Howard St., San Francisco, CA 94103',
    'description': 'A chance to hear more about Google\'s developer products.',
    'start': {
      'dateTime': isoStartDate,
      'timeZone': timeZone
    },
    'end': {
      'dateTime': isoEndDate,
      'timeZone': timeZone
    },
    'attendees': [
      {'email': '[email protected]'},
      {'email': '[email protected]'}
    ],
  }

Upvotes: 1

Related Questions