Denilson Sá Maia
Denilson Sá Maia

Reputation: 49377

How to create a Date() with a specific timezone, in Google Apps Scripts

I want to create a Calendar event using the same timezone as the calendar.

I already have the year, month and day as numbers, in separate variables. How can I construct a Date object using these values, in a specific timezone?

var day = 31;
var month = 11;  // Month is zero-based
var year = 2014;
var timezone = calendar.getTimeZone();

// How to add the timezone here?
var date = new Date(year, month, day, 12, 0, 0);

Essentially, I ask this because of the documentation:

If no time zone is specified, the time values are interpreted in the context of the script's time zone, which may be different than the calendar's time zone.

Thus I wish to know how to correctly specify the timezone.


Relevant blog post (although it doesn't answer my question):

Upvotes: 4

Views: 16806

Answers (3)

Neo
Neo

Reputation: 817

You can get the timezone of the script and then load it into the parameters.

var timeZone = Session.getScriptTimeZone();
var timeStamp = Utilities.formatDate(new Date(), timeZone, "dd-MM-yyyy | HH:mm:ss");

Now you can use the timeStamp in your code.

Upvotes: 4

Cyrus Loree
Cyrus Loree

Reputation: 847

Not sure if this is what you're looking for.

The code below takes into consideration the calendar timezone and the Session / Script timezone, and adjusts the offset.

var day = 31;
var month = 11;  // Month is zero-based
var year = 2014;
var timezone = calendar.getTimeZone();

// How to add the timezone here?
var date = new Date(year, month, day, 12, 0, 0);

// get the timezones of the calendar and the session
var calOffset = Utilities.formatDate(new Date(), timezone, "Z");
var scriptOffset = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "Z");

// remove the 0s
var re = /0/gi;
calOffset = parseInt(calOffset.replace(re,''));
scriptOffset = parseInt(scriptOffset.replace(re,''));

var offsetDif =   calOffset - scriptOffset;
var date = new Date();
// set the offset difference between the Session / Script and the calendar
date.setHours(date.getHours() +offsetDif);

Upvotes: -1

Serge insas
Serge insas

Reputation: 46792

From the documentation you referred to, about the method createEvent,, they show an example that creates an event on July 20 , 1969 , they create the date like this:

new Date('July 20, 1969 20:00:00 UTC')

You could do it like that, replace UTC with the time zone you want. Use the official time zone name instead of GMT+X so the daylight saving will be automatically calculated. (Didn't test recently but it used to work - I have no computer right now to test this before posting, sorry )

You can get the calendar tz in the script using cal.getTimeZone where cal is a calendar object.

I assumed that you wanted to keep your script settings in a tz different from the tz of the calendar? Otherwise it is obviously simpler to set all tz on the same value.

Upvotes: 0

Related Questions