google-sheetsgoogle-apps-script

Google App Script Copy New Date +7 Day not work


I'm trying to get a new Date with +7 day from the Google sheet and put in new Cell but it's not working for before month and after the month as present.

var current_date = datasheet.getRange(j,1).getValue();
      var next_date =  new Date();
      next_date.setHours(0,0,0,0);
      next_date.setDate(current_date.getDate()+7);
      ssTimeZone = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();
      datasheet.getRange(lastRow,1).setValue(Utilities.formatDate(next_date, ssTimeZone, 'dd.MM.yyyy'));

                                                            

When I try for July it gives me my +7 day of Oct and if I try December it will also give Oct date

This Date to +7 Day

05.05.2024
03.05.2024
07.05.2024

After Run Script Result Give

12.10.2024
10.10.2024
14.10.2024

Solution

  • It would probably be easier to adjust those dates using plain vanilla spreadsheet formulas, but because the Sheets–Apps Script automatically converts dates between the two, something like this should be enough in Apps Script:

      const date = datasheet.getRange(j, 1).getValue();
      date.setDate(date.getDate() + 7);
      datasheet.getRange(lastRow, 1).setValue(date);
    

    See: