How to add days to a date from Google Sheets?

前端 未结 1 1104
不思量自难忘°
不思量自难忘° 2020-12-10 05:45

I can\'t figure out how to add days to a date from Google Sheets with Google Apps Script.

for (var i = 0; i < data.length; ++i) {
    var row = data[i];
          


        
1条回答
  •  抹茶落季
    2020-12-10 06:24

    There are probably many ways to do that, here are 2 of them

    1. Knowing that native value of JavaScript Date are milliseconds, you can add n times 3600000*24 milliseconds to this native value, n being the number of days.
    2. or you can get the day value, add n to this value and rebuild the date with that. To get the day simply use getDate(). See doc on JS date here.

    Below is a simple demo function that uses both methods and shows results in the logger :

    function myFunction() {
      var data = SpreadsheetApp.getActive().getActiveSheet().getDataRange().getValues();
      for (var i = 0; i < data.length; ++i) {
        var row = data[i];
        var car = row[1];
        var date = new Date(row[2]); // make the sheet value a date object
        Logger.log('original value = '+date);
        Logger.log('method 1 : '+new Date(date.getTime()+5*3600000*24));
        Logger.log('method 2 : '+new Date(date.setDate(date.getDate()+5)));
      }
    }
    

    enter image description here

    0 讨论(0)
提交回复
热议问题