Adding Days to a Date - Google Script

2019-04-07 09:18发布

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

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

if ((car == "Car1") || (car == "Car2")) {
        var newDay = new Date(date + 154);
        Logger.log(newDay);
}

I've tried using new Date(date.add({days: 154})); But that throws an error about not finding add() in the object.

I thought it may be a formatting issue, in Sheets the format is 7/26/2014.

1条回答
你好瞎i
2楼-- · 2019-04-07 10:05

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

查看更多
登录 后发表回答