[英]How do I loop adding the month to each date until the condition is met? google apps script
How do I loop adding the month to each date until the condition is met?如何循环将月份添加到每个日期直到满足条件?
Explanation: I want to add 3 months to each date every time until the annual column (column D) will be greater than the today's date ( column E).说明:我想每次都向每个日期添加 3 个月,直到年度列(D 列)大于今天的日期(E 列)。
Example: If we took the first line of the column Annual " 01/02/2021" and we add at first 3 months the results will be 01/05/2021 then we add second time 3 months 01/08/2021..etc until it will be 01/05/2022 ( Greater than the today's date).示例:如果我们在年度“01/02/2021”列的第一行添加前 3 个月,结果将为 01/05/2021 然后我们添加第二次 3 个月 01/08/2021..etc直到 01/05/2022(大于今天的日期)。
In the column "H" I've write the results I want, but whats I've got is in the column "F" by Red.在“H”列中,我写下了我想要的结果,但我得到的是在“F”列中的 Red。
Here's my code:这是我的代码:
function myFunction() { var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1'); for (var i = 2; i < 12; i++) { var today_date = ss.getRange(i, 5).getValue(); var today_date_format = Utilities.formatDate(new Date(today_date), "Europe/Paris", 'MMMM dd, yyyy 12:00:00 Z'); var Date_2021 = ss.getRange(i, 4).getValue(); var Date_2021_Format = Utilities.formatDate(new Date(Date_2021), "Europe/Paris", 'MMMM dd, yyyy 12:00:00 Z'); var Date_2021_constructed = new Date(Date_2021_Format); var a3date = Date_2021_constructed.getMonth(); Date_2021_constructed.setMonth((a3date + 3) % 12); do { Date_2021_constructed = Date_2021_constructed.setMonth((a3date + 3) % 12); } while (Date_2021_constructed > today_date_format); ss.getRange(i, 6).setValue(Date_2021_constructed) } }
Here's the screen of my data:这是我的数据屏幕:
Thanks for the example and the image that helps a lot:感谢您提供的示例和有很大帮助的图像:
I'm going to suggest a quick fix and see if it works.我将建议一个快速修复,看看它是否有效。 It looks like you may be posting the value of the date in millisecond in column f.
看起来您可能会在 f 列中以毫秒为单位发布日期值。 So try this:
所以试试这个:
ss.getRange(i, 6).setValue(new Date(Date_2021_constructed)).setNumberFormat("dd/MM/yyyy");
If this doesn't work I'll take a closer look and it would be helpful to have a table of values from your spreadsheet so that I can test.如果这不起作用,我会仔细查看,从您的电子表格中获取值表会很有帮助,以便我进行测试。
If the above solution does not work then try this:如果上述解决方案不起作用,请尝试以下操作:
function myFunction() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');
const vs = sh.getRange(2,1,sh.getLastRow() - 1,5).getValues();
vs.forEach((r,i) => {
let td = new Date(r[4]);
let tdv = td.valueOf();
let ad = new Date(r[3]);
let m = r[2];
let n = 1;
do{
var fd = new Date(ad.getFullYear(),ad.getMonth() + (n++ * m), ad.getDate());
var fdv = fd.valueOf();
}while(fdv<tdv);
sh.getRange(i + 2,6).setValue(fd).setNumberFormat("dd/MM/yyyy");
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.