Google Apps Script – Date Manipulation in GAS Script

google sheetsgoogle-apps-script

I am trying to add 7 days to the current date and name a sheet with that value. Below is the code I would think would work, but it keeps the date format and adds the 7 days to the year rather than the day.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var tz = ss.getSpreadsheetTimeZone();
var sheets = ss.getSheets();
var date = Utilities.formatDate(new Date(), tz, 'MM-dd-yy');
var day1 = date +7
sheets[1].setName(day1);  // Rename second   

Do I have something incorrect?

Best Answer

Short answer

Use setDate JavaScript method.

Explanation

Google Apps Script use JavaScript to handle date objects, so you should use JavaScript methods instead of typical Google Sheets methods.

By the other hand, Utilities.formatDate() returns a string, not a date object.

The following script set the name of the second sheet as the date of seven days from now:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var tz = ss.getSpreadsheetTimeZone();
  var date = new Date();
  var nextDate = new Date();
  var days = 7;
  nextDate.setDate(date.getDate() + days);
  var stringDate = Utilities.formatDate(nextDate, tz, 'MM-dd-yy');
  ss.getSheets()[1].setName(stringDate)
}

References

Add days to JavaScript Date