0

I have a script to add a week to C (oldDateRange) and put the result in D (NextWeek) but it's not working well.

I'm also need to add a week to D and put the result in E. If I change C, columns D and E add a week. If I change D, E add a week.

function addWeek() {

var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");

var oldDate  = sheet.getRange("oldDateRange").getValue();

var oldDateValue = oldDate.getMilliseconds()

var nextWeekValue = oldDateValue + 1000*60*60*24*7
var nextWeekDate = new Date(nextWeekValue)

var cell = sheet.getRange("NextWeek"); 
cell.setValue(nextWeekDate);

}  
Mary
  • 13
  • 1
  • 4

1 Answers1

0

The answer is to add 7 to the old Date property and set the new Date with it. The answer can be found here. Add days to JavaScript Date.

function addWeek() 
{

  var ss = SpreadsheetApp.getActive();
  // I just added the id for accuracy

  var sheet = ss.getSheetByName("Sheet1");

  var lrow = sheet.getLastRow();
  // get the last row in the spreadsheet so when know when to stop for our 
  //loop

  var oldDates = sheet.getRange(2, 4, lrow, 1).getDisplayValues();
  //the displayvalue returns whatever is in the cell

  var newDates = sheet.getRange(2, 5, lrow, 1);
  Logger.log(newDates.getDisplayValues().length);
  // I get the range instead of the value because I will set values here.  

  for(var i = 1; i < lrow;i++)
  {
    var date = new Date(oldDates[i][0]); 
    // gets the current date cell and creates a date from it
    var newDate = date;
    // creates a new date
    newDate.setDate(date.getDate() + 7);
    //sets the date adding a week
    newDates.getCell(i, 1).setValue(newDate);
   //sets the cell to the right with the date.
  }
}
John Thompson
  • 386
  • 3
  • 10
  • I tried the code but it's not working for me. I change var newDate2 = new Date(oldDate.getDate() + 7); but not working. I'm reading this link: https://developers.google.com/google-ads/scripts/docs/features/dates – Mary Nov 08 '18 at 14:28
  • Here my sheet https://docs.google.com/spreadsheets/d/1B-nWMSUBhK8DKoKp7uQMwuH4RNrNwsmfsgnCqK2mV6Y/edit#gid=0 – Mary Nov 08 '18 at 14:28