如何在Google Apps Scripts中创建具有特定时区的Date()

时间:2014-08-08 16:24:47

标签: date google-apps-script timezone

我希望create a Calendar event使用与日历相同的timezone

我已将年,月,日作为数字,在单独的变量中。如何在特定时区使用这些值构建Date对象?

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);

基本上,我问这是因为documentation

  

如果未指定时区,则在脚本的时区上下文中解释时间值,该时区可能与日历的时区不同。

因此,我想知道如何正确指定时区。


相关博客文章(虽然它没有回答我的问题):

3 个答案:

答案 0 :(得分:0)

从你提到的文档中,关于方法createEvent,他们展示了一个在1969年7月20日创建事件的例子,他们创建了这样的日期:

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

您可以这样做,将UTC替换为您想要的时区。使用官方时区名称而不是GMT + X,以便自动计算夏令时。 (最近没有测试,但过去常常工作 - 我现在没有电脑在发布前测试这个,抱歉)

您可以使用cal.getTimeZone在脚本中获取日历tz,其中cal是日历对象。

我认为您希望将脚本设置保持在与日历的tz不同的tz中?否则,将所有tz设置为相同的值显然更简单。

答案 1 :(得分:0)

不确定这是否是您正在寻找的。

以下代码会考虑日历时区和会话/脚本时区,并调整偏移量。

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);

答案 2 :(得分:0)

您可以获取脚本的时区,然后将其加载到参数中。

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

现在您可以在代码中使用timeStamp