gpt4 book ai didi

javascript - App scripts new Date 和 getTime 的行为不像在浏览器中那样

转载 作者:行者123 更新时间:2023-11-30 11:13:02 25 4
gpt4 key购买 nike

在我的浏览器控制台中,我能够解析日期并以毫秒为单位获取时间:

new Date('2018-10-16 12:41:50.000000');
// => Tue Oct 16 2018 12:41:50 GMT+0200 (Central European Summer Time)
new Date('2018-10-16 12:41:50.000000').getTime();
// => 1539686510000

如果我在 App 脚本中做同样的事情,日期将无法识别(默认为 1970 纪元)并且 getTime() 会中断 (NaN):

function test_date() {
Logger.log('new Date(date)');
Logger.log(new Date('2018-10-16 12:41:50.000000'));
Logger.log('getTime()');
Logger.log(new Date('2018-10-16 12:41:50.000000').getTime());
}

enter image description here
enter image description here

我是不是遗漏了什么或者 new Date()/getTime() 只是在 App 脚本中损坏了?

我在 Google 表格中运行上述脚本

最佳答案

Google Apps 脚本使用 RFC3339。所以2018-10-16 12:41:50.000000不能被new Date('2018-10-16 12:41:50.000000')直接解析。这样,new Date('2018-10-16 12:41:50.000000')new Date('')是一样的,结果都变成了1970 年 1 月 1 日星期四 01:00:00 GMT+01:00。为了解析日期,修改成RFC3339格式怎么样?

来自:

Logger.log(new Date('2018-10-16 12:41:50.000000'));
Logger.log(new Date('2018-10-16 12:41:50.000000').getTime());

收件人:

Logger.log(new Date('2018-10-16T12:41:50.000Z'));
Logger.log(new Date('2018-10-16T12:41:50.000Z').getTime());

结果:

Tue Oct 16 12:41:50 GMT+02:00 2018
1.53968651E12

备注:

  • 在您的情况下,在 Google Apps 脚本中,脚本的时区会反射(reflect)到结果中。这种情况的时区可以在脚本编辑器中看到。
    • 在脚本编辑器上。
      • 文件 -> 项目属性 -> 信息 -> 时区
    • 您也可以通过脚本的Logger.log(Session.getScriptTimeZone())来确认。
  • new Date('2018-10-16T12:41:50')也可以解析。

引用资料:

如果这不是您想要的,我很抱歉。

关于javascript - App scripts new Date 和 getTime 的行为不像在浏览器中那样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52887851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com