1
votes

I have 3 variables: (1)Date (2) StartTime (3) EndTime I would like to bring them as two variables (1)Date and StartTime (2) Date and EndTime, so that I can create a google calendar event.

As per my understanding, in order to create a google calendar event I need to pass ISO String format for event timings. Can anyone check the below code and help me with the missing piece.

 function createEvent(title,Dt,startTime,endTime,col) {
 var calendarId = '[email protected]';
 Logger.log(Dt); //2016-07-21
 Logger.log(startTime); // 11:55 AM
 Logger.log(typeof(startTime)); //string


 //Help Needed to convert + to ISO

 var event = {
 summary: title,
 start: {
 dateTime: startISO
 },
 end: {
 dateTime: endISO
 },
 colorId: col
 };
 event = Calendar.Events.insert(event, calendarId);
 Logger.log('Event ID: ' + event.getId());
1
you can get ISO by following three steps, 1) Convert your time from am/pm to 24 hours as 11:55 AM = 11:55 and 11:55 PM = 23:55, 2) then concatenate both date and time with space like 2016-07-21 11:55 and then 3) get date from string as var date = new Date("2016-07-21 11:55"); which will be ISO date - Vickyexpert

1 Answers

2
votes

You can use .toISOString() on the Date object to get an ISO String, but Google Calendar is requesting a slightly different format than this, but it is a quick fix. Start with a normal conversion:

(new Date()).toISOString(); // "2016-07-29T00:00:00.000Z"

var startTime = new Date();
var isoStartTime = startTime.toISOString();

If you need to make the Date from separate objects you can:

var yourDate = '2016-07-29';
var yourTime = '11:55 AM';

var startTime = new Date(yourDate);
startTime.setHours(yourTime.split(':')[0]); // 11
startTime.setMinutes(yourTime.split(':')[1].substr(0,2)); // 55

startTime = startTime.toISOString(); // "2016-07-29T11:55:00.000Z"

Then change it to what Google's looking for:

// To RFC 3339...
startTime.substr(0,startTime.length-5)+'Z'; // "2016-07-29T11:55:00Z"

Or

//if the "startTime = startTime.toISOString()" assignment happened
startTime.split('.')[0]+'Z';

//if startTime is a Date object, not a string
startTime.toISOString().split('.')[0]+'Z';

You can also (and probably preferrably) use numbers instead of strings for all that; if you pass hours and minutes separately it could look cleaner than that string operation:

var startTime = new Date(yourDate);
startTime.setHours(yourHours); // string or int
startTime.setMinutes(yourMinutes); // string or int