简体   繁体   中英

GAS gets wrong date from spreadsheet

I'm having trouble with GAS picking up the right date from my spreadsheet.

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?

Print Screen of debug

GAS uses the standard JavaScript Date object. 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).

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. When you assign d1 to another variable it does NOT copy the object (as you would expect from two integer values). 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. According to JS documentation, the setDate() method "sets the day of the Date object relative to the beginning of the currently set month". Calling the method on a Date object will affect the object located on the left of the dot.

The code below is a workaround based on creating a temporary object. Because months are zero-indexed, 6 would be July.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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