首页 > 解决方案 > 如何将日期对象和时间对象组合成 DateTime 对象并作为 DateTime 对象存储在谷歌表中

问题描述

我有一个日期对象和一个时间对象,我想将它们组合成一个日期时间对象,而不是作为字符串,而是作为一个日期时间对象,我可以存储它以便以后针对其他日期时间对象进行测试。像这样的所有问题似乎都处理日期时间的字符串格式。

我尝试简单地将两个对象添加在一起,这适用于工作表的两个元素,但不适用于脚本变量。

var lastDayPumpOn = new Date();
lastDayPumpOn = lastPumpDate + lastPumpTime;
Browser.msgBox('Last on time = '+lastDayPumpOn);

这个简单的加法产生的东西似乎是零时间的日期和零日期的时间的串联。我不清楚它实际上是一个日期时间对象还是某个字符串。

标签: datedatetimegoogle-apps-scripttime

解决方案


JavaScript 中没有“时间”或“日期时间”对象,只有Date

为什么你得到一个字符串,而不是一个新的日期

如果要将存储在 Date 对象中的毫秒数相加,则必须注意两个参数确实是Date对象或数字(表示毫秒),并在变量中使用.getTime()a 或前缀 a+来获取毫秒数。

// this assumes lastPumpTime is some Date that has had its date component "zeroed out"
var lastDayPumpOn = new Date(lastPumpDate.getTime() + lastPumpTime.getTime()); // construct new Date from milliseconds argument
// or
var lastDayPumpOnAlt = new Date(+lastPumpDate + +lastPumpTime); // implicitly using Date.prototype.valueOf
// lastDayPumpOn.getTime() === lastDayPumpOnAlt.getTime() is true
Browser.msgBox('Last on time = ' + lastDayPumpOn); // implicitly calls lastDayPumpOn.toString()

如果 a 周围的任一变量+是字符串,则结果将是字符串。.toString任何对象都会隐式调用它们的函数。

清零日期部分

要创建“时间”对象(没有日期部分的日期),有多种方法,其中一种是将日期部分设置为 1970 年 1 月 1 日

lastPumpTime.setFullYear(1970);
lastPumpTime.setMonth(0); // Jan === 0, zero indexed
lastPumpTime.setDate(1);

现在lastPumpTime.getTime()是比 24 小时的毫秒数少几毫秒。


推荐阅读