0

I'm trying to process a form with a datetime-local field to create a calendar event in a public google calendar. But when I run the program, all my dates default to December 31st 1969 at 4pm. Anyone have any ideas?

My script (which takes "form" as a parameter):

var event = cal.createEvent(form.myTitle, new Date(form.startTime+".000Z"), new Date(form.endTime+".000Z"));
Logger.log(form.startTime+" and "+form.endTime);

I added ".000Z" as per this solution, but I ran into the same problem even without adding it: Why does my Date object in Google Apps Script return NaN

What startTime and endTime are logged as:

2016-03-15T17:30 and 2016-03-15T19:30

But this is in the execution transcript:

Calendar.createEvent([NEW EVENT, Wed Dec 31 16:00:00 PST 1969, Wed Dec 31 16:00:00 PST 1969])
Community
  • 1
  • 1
hbth
  • 1

1 Answers1

0

There are lots of ways to set a date object in JavaScript, but to set the correct date for a Google Calendar, you must do it in a very specific way. You must get the calendar time zone. For many people, if the users of their script are all in the same time zone, then the code will work. The problem comes when you have users across different time zones, or the time zone of the script is different than the time zone of the calendar. The code must construct a valid date string first, and then use the date string to create the date object. You can create a date object without a date string, and that would be preferable in most cases, because people can mess up the code to create the date string, but in this situation, you have no other choice (That I know of). Why? It's because of the time zone offset setting. The time zone offset setting is included in the date string. That is the key piece of information, that makes sure your dates will get set correctly, including for daylight savings.

function setCalendarEvent(){

  var startTime = "2016-03-15T17:30";
  var endTime = "2016-03-15T19:30";

  //Always get the time zone of the calendar.  If you don't do that, users accross different times zones will write bad dates
  var calTimeZone = CalendarApp.getDefaultCalendar().getTimeZone();

  //Construct a valid date string from the data
  var startYr = startTime.slice(0,4);
  var endYr = endTime.slice(0,4);

  var startMonth = startTime.slice(5,7);
  var endMonth = endTime.slice(5,7);

  var startDay = startTime.slice(8,10);
  var endDay = endTime.slice(8,10);

  var startHrAndMin = startTime.slice(11,17);
  var endHrAndMin = endTime.slice(11,17);

  var startDateString = startMonth + "/" + startDay + "/" + startYr + " " + startHrAndMin + ":00 ";

  var timeZoneOffset = Utilities.formatDate(new Date(startDateString),calTimeZone, "Z");

  var startDateAsDate = new Date(startDateString + " " + timeZoneOffset);

  Logger.log('startDateAsDate: ' + startDateAsDate)
};
Alan Wells
  • 30,746
  • 15
  • 104
  • 152