知道日期是否晚于 10 天的最简单方法可能是计算毫秒数!
我知道这听起来像个笑话,但事实并非如此;-)
例子 :
function test(){
var today = new Date();
var tendaysBefore = new Date(today.getTime()-10*24*60*60*1000);// 10 times 24 hours
Logger.log(today+' is 10 later than '+tendaysBefore);
}
getTime() 方法返回从参考日期开始的毫秒数,它将工作到 2070 年,所以我想现在可以安全使用 ;-)
科尼利厄斯的回答已经解决了触发问题,谢谢
编辑:这是一个可能的代码来做你想做的事:(在你的工作表上测试)
var sh = SpreadsheetApp.getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();// replace these with openbyId''ID') and getSheetByName(name) when you run it with trigger since the sheet wil be 'closed'
var lastrow = ss.getLastRow();
function onOpen() {
var menuEntries = [ {name: "check late paiments", functionName: "test"},
{name: "send mails to tagged users", functionName: "mailunpaid"},
];
ss.addMenu("custom functions",menuEntries);// custom menu
}
function test(){ // check column D and set it to "no" if not paid
var paidcol = sh.getRange(2, 4, lastrow-1, 1).getValues();//read only col D
for(nn=0;nn<paidcol.length;++nn){
if(paidcol[nn][0].toString().toLowerCase().match('yes')!='yes'){
paidcol[nn][0]='no'
}
}
sh.getRange(2, 4, lastrow-1, 1).setValues(paidcol);// write back to sheet
}
function mailunpaid(){
var data = sh.getDataRange().getValues();//read the whole sheet in an array, col D is idx3, timestamp is idx0 email is idx 23
var today = new Date();
var tendaysBefore = new Date(today.getTime()-10*24*60*60*1000);// 10 times 24 hours
for (nn=1;nn<data.length;++nn){ // iterate from row 2 to end ie idx 0 to last
// Logger.log(data[nn][3]+' '+data[nn][0])
if(data[nn][0]<=tendaysBefore && data[nn][3]=='no'){
// MailApp.sendEmail(data[nn][23], 'subject', 'body'); // you have to define the mail subject & content somewhere ;-) and uncomment when finished your tests
Logger.log('row '+Number(nn+1)+' = to send because '+data[nn][0])
sh.getRange(nn+1,4).setValue('SENT');// tag this user to know that mail has been sent to avoid multiple emails
}
}
}
请注意,为了清楚起见,我将代码拆分为 2 个函数,但是当它作为触发器运行时,您应该将这两个函数组合在一起以进行自动检查...