Looping through a google sheet to remove rows - Compare dates - google-apps-script

The code needs to delete rows have a date before the current date. I'm not getting any syntax errors, but I think there is a semantic problem as the code will not change the spreadsheet in any way.
function checkDateValue(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var todaysDate = new Date().getDate();
var columnGCells = sheet.getRange("G2:G");
var columnG = columnGCells.getValues();
for (i = 1; i < sheet.height; i++) {
var endDate = new Date()
endDate = columnG[i];
if (todaysDate.getYear() >= endDate.getYear()){
if (todaysDate.getMonth() >= endDate.getMonth()){
if (todaysDate.getDay >= endDate.getDay()){
sheet.deleteRow(i);
}
}
}
}
};
checkDateValue();

The code would probably look something like this:
function checkDateValue(e) {
var colG_values,columnGCells,columnNumber,endDate,i,lastRow,
sheet,startRow,todaysDate;
startRow = 2;//Get data starting in this row
columnNumber = 7://The column number to get the data from
sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
lastRow = sheet.getLastRow();
todaysDate = new Date().getDate();
//Logger.log('todaysDate: ' + todaysDate);
columnGCells = sheet.getRange(startRow,columnNumber,lastRow-1,1);
colG_values = columnGCells.getValues();
for (i = lastRow; i > 1; i--) {//Loop through values from last to first-
//Need to stop at row one-
endDate = colG_values[i];
endDate = new Date(endDate);
if (todaysDate.getYear() >= endDate.getYear()){
if (todaysDate.getMonth() >= endDate.getMonth()){
if (todaysDate.getDay >= endDate.getDay()){
sheet.deleteRow(i);//Delete this row
}
}
}
};
};
function runTest() {
checkDateValue();
};

Related

AppScript Select active range

so i am trying to when i select any column form the row, returns me the column E value, some one know how?
i don't know if i made me clear, but the idea is save the value and display after in a sidebar as default value
i have onde function who does something similar, but i don't know how works
function notifyReporterForm() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_BUGS);
var row = ss.getLastRow(), column = 1, numRows = 1, numColumns = ss.getLastColumn();
var values = ss.getRange(row, column, numRows, numColumns).getValues();
var to = values[0][2];
var user_email = values[0][3];
var ticketNo = values[0][0];
var openedDate = values[0][1]
var details = ''
var summary = values[0][6]
var text = values[0][6].split('\n')
var image_url = values[0][8]
text.map(row => {
if(row){
details += '<p>' + row + '</p>'
}
})
function onSelectionChange(e) {
const sh = e.range.getSheet();
e.source.toast(sh.getRange(e.range.rowStart,5).getValue());
e.range.setValue(sh.getRange(e.range.rowStart,5).getValue());
}

Google Script timing out when grabbing rows from Database (MYSQL)

function myFunction() {
var ServerIP = 'xxx.xxx.xxx.xxx';
var SQL_Port = '3306';
var SQL_Usr = 'GDriveUser';
var SQL_Pwd = '**********';
var SQL_DB = 'wordpress_10';
var connectorInstance = 'jdbc:mysql://' + ServerIP+':'+SQL_Port;
var ConnectString = connectorInstance+'/'+SQL_DB;
var conn = Jdbc.getConnection(ConnectString, SQL_Usr, SQL_Pwd);
conn.setAutoCommit(false)
var SQLstatement = conn.createStatement();
var result = SQLstatement.executeQuery("SELECT * FROM `TABLE35` WHERE Team in ( 'atl', 'bkn', 'bos', 'cha', 'chi', 'cle', 'dal', 'den', 'det', 'gsw') and Date > 20201201 ORDER BY Date ASC");
var ss = SpreadsheetApp.openById("1QTv67oSTYnwsD0kwd0sDubzAor19pfAVngubjePqtzJg");
var sheet = ss.getSheetByName("Imported");
var cell = sheet.getRange('A2');
// loop through result object, setting cell values to database data
var row = 0;
while(result.next()) {
for(var i=0; i<23; i++) { // four fields per record
cell.offset(row, i).setValue(result.getString(i+1));
}
row++;
}
result.close();
SQLstatement.close();
conn.close();
}
This Google Script is only putting about 150 rows into my Google Sheet and then it times out.
Can someone help me find a fix for this?
Something like this:
function myFunction() {
var ServerIP = 'xxx.xxx.xxx.xxx';
var SQL_Port = '3306';
var SQL_Usr = 'GDriveUser';
var SQL_Pwd = '**********';
var SQL_DB = 'wordpress_10';
var connectorInstance = 'jdbc:mysql://' + ServerIP+':'+SQL_Port;
var ConnectString = connectorInstance+'/'+SQL_DB;
var conn = Jdbc.getConnection(ConnectString, SQL_Usr, SQL_Pwd);
conn.setAutoCommit(false)
var SQLstatement = conn.createStatement();
var result = SQLstatement.executeQuery("SELECT * FROM `TABLE35` WHERE Team in ( 'atl', 'bkn', 'bos', 'cha', 'chi', 'cle', 'dal', 'den', 'det', 'gsw') and Date > 20201201 ORDER BY Date ASC");
var ss = SpreadsheetApp.openById("1QTv67oSTYnwsD0kwd0sDubzAor19pfAVngubjePqtzJg");
var sheet = ss.getSheetByName("Imported");
var cell = sheet.getRange('A2');
// loop through result object, setting cell values to database data
var row = 0;
let oA=[];
sheet.getRange(2,1,sheet.getLastRow()-1,sheet.getLastColumn()).clearContent();//clear content before writing
while(result.next()) {
let rA=[];
for(var i=0; i<23; i++) {
rA.push(result.getString(i+1));
}
oA.push(rA);
}
sheet.getRange(2,1,oA.length,oA[0].length).setValues(oA);//starts at row 2 every time
result.close();
SQLstatement.close();
conn.close();
}

How to create a google app script that delete temporary contacts after a while?

i'm looking to create an script that does the following:
Delete a contact marked to be deleted after an specific time.
Surely you have save a phone number you are only going to use once, so this would help to delete that contact of we forgot about it.
Ok, i'm answering my own question for if someone is interested.
First, you have to create a contact group in wich you are going to categorize this contacts (in the code is "Tiny", but you can named as you whish).
Second, when creating a contact, you should add a note like; "2 month" if you want the contact to get erased after 2 months, or "1 year", etc. The code is implemented only for months and year, but is easily modifiable if you want another time period, like days or weeks.
Here's the code:
function deleteTinyContacts() {
var group = ContactsApp.getContactGroup("Tiny");
var contacts = ContactsApp.getContactsByGroup(group)
var hoy = new Date();
Logger.log("today is " + hoy);
Logger.log("total contacts to delete: " + contacts.length);
for (var i = 0; i < contacts.length; i++) {
var date = contacts[i].getLastUpdated();
Logger.log(contacts[i].getFullName() + " was updated last in " + date);
var datediff = DateDiff.inMonths(date,hoy);
Logger.log("contact updated " + datediff + " months ago");
var note = contacts[i].getNotes();
var res = note.split(" ");
var Tmonths = calcMonths(res[1]);
var todelete = res[0]*Tmonths;
Logger.log("contact must be deleted after " + todelete + " months");
if (datediff>=todelete){
group.removeContact(contacts[i]);
}
}
}
var DateDiff = {
inDays: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000));
},
inWeeks: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000*7));
},
inMonths: function(d1, d2) {
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
return (d2M+12*d2Y)-(d1M+12*d1Y);
},
inYears: function(d1, d2) {
return d2.getFullYear()-d1.getFullYear();
}
}
function calcMonths(str){
if(str=="año"){return 12;}
else if(str=="mes"){return 1;}
}

Google Script Not Iterating Through Rows

I have a google script that changes the event dates to the day of the year, so 8/26/15 is 237, and also changes today's date to it's day of the year. It then compares the event date day of the year against today's date day of the year. If the event date integer is smaller than today's date integer than it changes the event description in the google calendar to Event Closed. The problem is it only does this for the first event in the spreadsheet. It does not iterate through all of the events and change all of the event descriptions that are before today's date.
function compareDates(){
var sheet = SpreadsheetApp.getActive().getSheetByName("Events");
var data = sheet.getDataRange().getValues();
var headerRow = 1;
var i = 1;
for (i = 1; i < data.length; i += 1) {
var row = data[i];
var room = row[5];
var description = row[6];
var agegroup = row[7];
var registration = row[8];
var calname = row[14];
var registrants = row[17];
var id = sheet.getRange(headerRow + 1, 16).getValues();
var event = CalendarApp.getEventSeriesById(id);
var description1 = (description + '\n' + '\n<b>Room:</b> ' + room + '\n' + '\n<b>Event Type:</b> ' + calname + '\n' + '\n<b>Age Group:</b> ' + agegroup);
var today = parseInt(Utilities.formatDate(new Date(sheet.getRange("U2").getValues()), "EST", "D"));
var eventDate = parseInt(Utilities.formatDate(new Date(row[0]), "EST", "D"));
var testED = sheet.getRange(headerRow + i, 22).setValue(eventDate);//To see if var Today works.
var testT = sheet.getRange(headerRow + i, 23).setValue(today);//To see if var eventDate works.
if (today > eventDate && registration === 'Y') {
var descriptionHTMLEC = '\n <div id="registration_button" ><a style="text-align:right;color:white!important;text-decoration:bold;background-color:rgb(121,183,138);background-image:-webkit-linear-gradient(top,rgb(221,75,57),rgb(121,183,138nnn ));color:#ffffff;border:1px solid rgba(0,0,0,0);border-radius:2px;display:inline-block;font-size:12px;font-weight:bold;height:27px;line-height:27px;padding:0px 20px 0px 20px;text-align:center;text-transform:uppercase;white-space:nowrap;text-decoration:none;color:white" target="_blank">Event Closed</a>';
var descriptionRegistrationEC = (description1 + '\n' + '\n' + descriptionHTMLEC);
event.setDescription(descriptionRegistrationEC);
}
}
}
It seems you are modifying the same event on each iteration. The statement:
var id = sheet.getRange(headerRow + 1, 16).getValues();
Will assign the same value to id each time. Shouldn't it be:
var id = sheet.getRange(headerRow + i, 16).getValues();
For more readable code you can just the getTime() function on the date object.
var today = new Date(sheet.getRange("C2").getValues()).getTime();
var eventDate = new Date(row[0]).getTime();

Google Apps Script - deleting a row if today's date is past input date

I'd like to make a script that compares the date within a row to today's date and delete that row if today's date is paste the date row.
This is my current script:
function deleteRow1() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1; // First row of data to process
var numRows = sheet.getLastRow()-1; // Number of rows to process
var dataRange = sheet.getRange(startRow, 2, numRows);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i=0;i<data.length;i++) {
var row = data[i];
var date = new Date();
var sheetDate = new Date(row);
var Sdate = Utilities.formatDate(date,'GMT+0200','yyyy:MM:dd')
var SsheetDate = Utilities.formatDate(sheetDate,'GMT+0200', 'yyyy:MM:dd')
if (Sdate > SsheetDate){
sheet.deleteRow(i+2) //don't delete header
}
}
}
The ultimate goal is to compare dates in column C with today's date and to delete that particular row if today's date is greater.
Right now when I run the script, it deletes some rows, but not specifically the rows that are earlier than today's date.
The beginnings of this script was based off another StackOverflow post
when you start iteration from top to bottom deleting row in iteration alter the offset (actual row number) of next rows
above problem can be solved using start the iteration from bottom to top.
for (i=data.length-1;i>=0;i--)
here is the working code
function deleteRow1()
{
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow()-1; // Number of rows to process
var dataRange = sheet.getRange(startRow, 2, numRows);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i=data.length-1;i>=0;i--)
{
var row = data[i];
var date = new Date();
var sheetDate = new Date(row);
var Sdate = Utilities.formatDate(date,'GMT+0200','yyyy:MM:dd')
var SsheetDate = Utilities.formatDate(sheetDate,'GMT+0200', 'yyyy:MM:dd')
if (Sdate.valueOf() > SsheetDate.valueOf())
{
sheet.deleteRow(i+2) //don't delete header
}
}
}