Search code examples
javascriptdategoogle-apps-scriptgoogle-sheetsincrement

Increment date in Google Script


I want simply to increment a given date in Cell A1 by 1 day. I need two seperat variables, one for the given date and one variable for the new, incremented date. The problem is, that my code always change both variables and I dont know why.

function testDate() {

var sht_test = SpreadsheetApp.getActive().getSheetByName('Test');
var date_given = sht_test.getRange(1,1).getValue(); // type a Date in cell A1
var date_new;

date_new = date_given;
date_new = new Date(date_new.setDate(date_new.getDate() +1 ));  

sht_test.getRange(2,1).setValue(date_new);
sht_test.getRange(2,2).setValue(date_given);

}

Solution

  • Issue / Explanation:

    In this part of your code:

    date_new = date_given;

    you pass a reference of date_given to date_new.

    Namely, whatever changes you make on date_new are automatically applied to date_given since they refer to the same date object.

    When you increment the date by 1:

    date_new = new Date(date_new.setDate(date_new.getDate() +1 ));

    the part: date_new.setDate(date_new.getDate() +1 )

    increments (changes) date_new and therefore date_given is also modified since they both refer the the same object.

    This is why date_new and date_given return the same value.

    In order to separate them, you need to create a copy of date_given which will be a new date object:

    date_new = new Date(date_given);

    and therefore if you later modify date_new, date_given won't be modified.


    Solution:

    function testDate() {
    
    var sht_test = SpreadsheetApp.getActive().getSheetByName('Test');
    var date_given = sht_test.getRange(1,1).getValue(); // type a Date in cell A1
    var date_new;
    
    date_new = new Date(date_given);
    date_new = new Date(date_new.setDate(date_new.getDate() +1 ));  
    
    sht_test.getRange(2,1).setValue(date_new);
    sht_test.getRange(2,2).setValue(date_given);
    
    }