如何从 Google 表格向日期添加天数? [英] How to add days to a date from Google Sheets?

查看:31
本文介绍了如何从 Google 表格向日期添加天数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何使用 Google Apps 脚本从 Google 表格中为日期添加天数.

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];
    var car = row[1];
    var date = row[2];

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

我尝试过使用 new Date(date.add({days: 154})); 但这会引发关于在对象.

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

我认为这可能是格式问题,在表格中格式为 7/26/2014.

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

推荐答案

可能有很多方法可以做到这一点,这里是其中的两种

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

  1. 知道 JavaScript Date 的原生值是毫秒,你可以在这个原生值上加上 n 乘以 3600000*24 毫秒,n 是天数.莉>
  2. 或者您可以获得日期值,将 n 添加到该值并使用该值重建日期.要获得这一天,只需使用 getDate().查看 JS 日期的文档此处.莉>
  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)));
  }
}

这篇关于如何从 Google 表格向日期添加天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆