【问题标题】:How to create a Date() with a specific timezone, in Google Apps Scripts如何在 Google Apps 脚本中创建具有特定时区的 Date()
【发布时间】:2014-08-08 16:24:46
【问题描述】:

我想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

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

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


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

  • 在 Apps 脚本中揭开时区的神秘面纱 - part 1part 2

【问题讨论】:

    标签: date google-apps-script timezone


    【解决方案1】:

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

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

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

    【讨论】:

    【解决方案2】:

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

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

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

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

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

    【讨论】:

    • 所以,我需要将我的数字月份转换为英文,然后将所有内容连接成一个字符串。这可能可行,尽管我有点期待某种 API 直接设置/更改时区,而不使用字符串连接和解析。稍后我会测试。
    • 只是一个问题:您是否希望能够在本地时间值中输入时间或根据需要在某个绝对时间创建事件,例如在不同 tz 的 2 人之间安排约会?换句话说,您希望它如何工作?例如,在东京的 12:00 创建一个活动,或者在东京的 12:00 在这里的任何时间创建一个活动......?编辑:你看到那个帖子了吗? stackoverflow.com/questions/439630/…
    • 基本上,我想对时区进行一些控制,以确保我创建的事件位于正确的时区。 (但是,现在,一个人的单一事件)
    【解决方案3】:

    不确定这是否是您要查找的内容。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      相关资源
      最近更新 更多