简体   繁体   English

GAS从电子表格获取错误的日期

[英]GAS gets wrong date from spreadsheet

I'm having trouble with GAS picking up the right date from my spreadsheet. GAS从电子表格中选择正确的日期时遇到了麻烦。

As a test, I set the date to June 27, 2017 and subtracted one day from it, but debug shows both dates as Jun 26, 2017. How can that be? 作为测试,我将日期设置为2017年6月27日,并从中减去了一天,但是debug将两个日期都显示为2017年6月26日。那怎么可能?

Print Screen of debug 调试打印屏幕

GAS uses the standard JavaScript Date object. GAS使用标准的JavaScript Date对象。 Objects are reference types, not value types as Number or Boolean (Actually, everything in JS is an object and objects are associative arrays, but we'll leave that aside for the sake of clarity). 对象是引用类型,而不是数值类型(如Number或Boolean)(实际上,JS中的所有内容都是对象,并且对象是关联数组,但为清楚起见,我们将其放在一边)。

Suppose you initialize a date and assign it to another variable like this 假设您初始化一个日期并将其分配给另一个这样的变量

var d1 = new Date(2017, 6, 26);

var temp = d1;

In this example, the variable d1 contains a reference to where the date object is stored in memory. 在此示例中,变量d1包含对日期对象在内存中存储位置的引用。 When you assign d1 to another variable it does NOT copy the object (as you would expect from two integer values). 当您指定D1到另一个变量它不会复制对象(如你会从两个整数值期望的那样)。 Instead, it creates another reference, but both variables are pointing to the same object in memory! 而是创建另一个引用,但是两个变量都指向内存中的同一对象!

Now it's much easier to understand why calling setDate() on your Date object modifies the original date variable. 现在,更容易理解为什么在Date对象上调用setDate()会修改原始date变量。 According to JS documentation, the setDate() method "sets the day of the Date object relative to the beginning of the currently set month". 根据JS文档,setDate()方法“相对于当前设置的月份的开始设置Date对象的日期”。 Calling the method on a Date object will affect the object located on the left of the dot. 在Date对象上调用该方法将影响位于点左侧的对象。

The code below is a workaround based on creating a temporary object. 下面的代码是基于创建临时对象的解决方法。 Because months are zero-indexed, 6 would be July. 因为月份是零索引的,所以6是7月。

var d1 = new Date(2017, 6, 26); //Logs Wed Jul 26 00:00:00 GMT+03:00 2017

var temp = new Date(d1.getTime());

var d2 = new Date(temp.setDate(temp.getDate() - 1)); //Logs Tue Jul 25 00:00:00 GMT+03:00 2017

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM