date - 如何将日期对象和时间对象组合成 DateTime 对象并作为 DateTime 对象存储在谷歌表中
问题描述
我有一个日期对象和一个时间对象,我想将它们组合成一个日期时间对象,而不是作为字符串,而是作为一个日期时间对象,我可以存储它以便以后针对其他日期时间对象进行测试。像这样的所有问题似乎都处理日期时间的字符串格式。
我尝试简单地将两个对象添加在一起,这适用于工作表的两个元素,但不适用于脚本变量。
var lastDayPumpOn = new Date();
lastDayPumpOn = lastPumpDate + lastPumpTime;
Browser.msgBox('Last on time = '+lastDayPumpOn);
这个简单的加法产生的东西似乎是零时间的日期和零日期的时间的串联。我不清楚它实际上是一个日期时间对象还是某个字符串。
解决方案
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 小时的毫秒数少几毫秒。
推荐阅读
- azure - 如何将多个自定义域添加到托管静态网站的 Azure 存储帐户?
- python - 使用 SpaCy 进行语法依赖提取?
- python - 绘制 SVC 决策区域
- apache-flink - 是否可以将 apache ranger/atlas 与 apache flink 集成?
- python - Scrapy:在爬取之前检查 MongoDB 是否有重复项
- spring-boot - 使用与 Spring Boot 存储库相同的存储库方法返回不同的 Dto
- apache-flink - Apache Flink 检查点不断失败
- box - FTPS MoveIt 无法下载没有扩展名的文件 - 不是普通文件 -
- chart.js - 由于标签过于紧凑,如何修复 X 轴中的网格线数量
- python - 我需要帮助在 python 中导航 api