Compare date with present date in google sheets script - google-apps-script

I want to compare the dates in Referral Date column with the present day and if Referral Date is lesser than present day then proceed with script if not throw an error "future date referral".
function dateFun() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Worksheet");
var headers = ss.getRange('A:Z').getValues()[0];
var column =headers.indexOf("Referral Date")+1;
var presentDay = new Date();
if (column.valueOf()>presentDay){
}else{
SpreadsheetApp.getUi().alert("Future Date Referral")
}
}
Image for reference
Hope its clear!

Date objects can be compared with logical operators.
Ok you are on the right track here, but you are missing some important methods to get the data from the spreadsheet.
function dateFun() {
// Open the worksheet
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Worksheet");
// Get data display values
var range = ss.getRange('A:Z');
// Get index of "Referral Date" in headers
var headers = range.getValues()[0];
var columnIndex = headers.indexOf("Referral Date")+1;
// Get today's date
var presentDay = new Date();
// Loop through the dates column
for(var i=1;i<=range.getNumRows();i++){
// Get the value to compare to today
var rowDate = new Date(range.getValues()[i+1][columnIndex]);
if(rowDate.valueOf()>presentDay.valueOf()){
SpreadsheetApp.getUi().alert("Future Date Referral");
}
}
}
Further reading:
Date()
getDisplayValue()

Related

Deleting row from google sheets that are older than 30 days but date column is plain text format

I have a Google Sheet that has entries with one of the Columns having a date when it's entered. I want the code to check if a date in Column E is older than 30 days and delete the row.
However, I have column E specifically formatted in plain text under the sheet options. The reason for doing so is I have a different script pull the data from the sheets as JSON and setting the column to plain text makes it show up as a string how I wanted in my JSON.
My code works if I format the column "E" in a date format.
Data is currently added as so "May 11th, 2021" whereas the closest date format in sheets is "May 11, 2021" without the "th" or "rd" after the dates but I would like to keep it how I have it if possible.
The code below works if Column E is formatted in date format but is there a way to get it to work as plain text format option which I currently have it set to?
Made a dummy Google Sheet for visual:
https://docs.google.com/spreadsheets/d/1_156bLL03lFo9NdjE6KmrGiFJvYXkvReel_9znMwT4M/edit?usp=sharing
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("sheet1"); //assumes Sheet 1 is the name of the sheet
var datarange = sheet.getDataRange();
var lastrow = datarange.getLastRow();
var values = datarange.getValues();// get all data in a 2D array
var monthOld = new Date()
monthOld = new Date(monthOld.getTime()-30*3600000*24) //Set date 30 days in past from today
Logger.log(monthOld) // confirm I am getting date 30 days ago
for (i=lastrow;i>=2;i--) {
var tempDate = values[i-1][4];// arrays are 0 indexed so row2 = values[1] and colE = [4]
Logger.log(tempDate)
if (tempDate <= monthOld)
{
sheet.deleteRow(i);
Logger.log(`Row ${i} was deleted`);
} else {
Logger.log(`Nothing was deleted`);
}
}
}
Try
var tempDate = new Date(values[i-1][4].replace(/(th|rd|st|nd)/gm,""));
Using the testbelow function as an intermediate function to pass the appropriate arguments to isOlderThan(). You pass the datestring in ds and the number of days in days. isOlderThan returns true or false based upon todays date.
function testbelow() {
isOlderThan({ds:"Jul 30th, 2021",days:30})
}
function isOlderThan(obj) {
const dA = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug"]
const dt = new Date();
const dtv = new Date(dt.getFullYear(),dt.getMonth(),dt.getDate() - obj.days).valueOf();
let t = obj.ds.split(" ");
let idtv = new Date(t[2],dA.indexOf(t[0]),parseInt(t[1])).valueOf();
Logger.log(idtv < dtv);
return idtv < dtv
}
Mike Steelson provided the line of code I needed to convert the plain text by parsing out the values that didn't apply and converting it to a date.
var tempDate = new Date(values[i-1][4].replace(/(th|rd|st|nd)/gm,""));

How to sum up date values to a number (days' sum)?

In Google Sheets I have a list of activities with a start date, and a number that specifies the duration in days of that activity. I need to use Google Apps Script to sum those numbers to the date, to obtain the deadline for the activity.
I've tried the solution posted in this question: Adding Days to a Date - Google Script.
The problem with that solution is that the script editor of the spreadsheet doesn't recognize the "Date" Class, so I can't instantiate a Date element.
Summing directly only takes the date and the number as a string.
Trying the method above results in a #NUM! error in the cell I want to convert.
EDIT:
I've tried this, where V3 holds the date I want to sum:
var fecha= new Date (ss.getSheetByName(camada).getRange("V3").getValue());
var fecha2= new Date();
fecha2.setDate(fecha.getDate() + 1);
ss.getSheetByName(camada).getRange("W3").setValue(fecha2);
It apparently works, but the problem is that V3 holds 5/13/2019 and the date returned is 4/14/2019, so it is a day more (13->14) but it is a month less (5->4).
The answer was in Adding Days to a Date - Google Script.
Three things:
don't define fecha2 as new Date(); this gives it no context and instead returns today's date.
let fecha2 be a variable name
the correct statement is var fecha2 = new Date(fecha.setDate(fecha.getDate() + 1));
function so55593876() {
var ss = SpreadsheetApp.getActiveSheet();
var range = ss.getRange("C3");
var value = range.getValue();
Logger.log("DEBUG: Date Range: "+range.getA1Notation()+", Date value: "+value);//DEBUG
var date = new Date(value); // make the sheet value a date object
Logger.log("DEBUG: new date(value) = "+date);//DEBUG
var dateTime = new Date(date.getTime()+1*3600000*24);
Logger.log("DEBUG: Method 1 (add one day = getTime()+1*3600000*24) = "+dateTime);//DEBUG
var dateDate = new Date(date.setDate(date.getDate()+1));
Logger.log('DEBUG: Method 2 (add one day = getdate()+1) = '+dateDate);//DEBUG
ss.getRange("C4").setValue(dateDate);
Logger.log("<<<<<<<<<<<FETCHA>>>>>>>>>>>>>");
var fecha = new Date(value); // make the sheet value a date object
Logger.log("DEBUG: fecha: new date(value) = "+fecha);//DEBUG
var fecha2= new Date(); // note there are no parameters; this will return TODAY's date
Logger.log("DEBUG: fecha2 = "+fecha2);//DEBUG
var fecha3 = fecha2.setDate(fecha.getDate() + 1);
Logger.log("DEBUG: fecha3 = "+fecha3); //DEBUG
var fecha2 = new Date(fecha.setDate(fecha.getDate() + 1));
Logger.log("DEBUG: fecha2 = "+fecha2); //DEBUG
ss.getRange("C5").setValue(fecha2);
}
I have left all the Logger statements in the code so that you can identify the various values at different states of the script.

My Javascript IF statement seems to think two identical values from a google sheets sheet do not match

I'm trying to write a script where the dates in a column are compared against todays date, and if the dates in the column match, an email is sent.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var rotDate = sheet.getRange("F6").getValue();
var today = sheet.getRange("F1").getValue();
//var today = new Date().toLocaleDateString(); // Today's date, without time
var dumpCell = sheet.getRange("J3");
var dumpCell2 = sheet.getRange("J4");
var dumpCell3 = sheet.getRange("J5");
if(rotDate==today) {
//dumpCell is there to dump a value in a cell if the IF statement is true
dumpCell.setValue(rotDate);
MailApp.sendEmail("this is where my email would go", "subject", "body");
}
//these dump the compared vars into cells so they can be checked against one another manually
dumpCell2.setValue(rotDate)
dumpCell3.setValue(today)
}
This is as far as I've gotten. The Values in F6 and F1 are identical, I've typed them out, retyped them, copied and pasted, etc. But for some reason, my if statement just won't run. It behaves as if the two values are different, and I can't work out why.
If I change var rotDate and var today to matching strings, eg "123" then it seems to work as expected.
This is a screenshot of my test data sheet. There are other columns there with other data which were meant to be used for more testing, but I didn't get that far.
Does anyone know what I might be doing wrong?
After trying a variety of approaches, I cracked it using a code snippet from Jon Lin's answer here:
Compare two dates Google apps script
After realizing that the fault was with trying to compare two dates (either a date in an adjacent cell, or a procedurally generated date whenever the function is run, I knew I had to do some better formatting with the data I was intending to compare. This is my repaired code that now works as expected:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var rotDate = sheet.getRange("F6").getValues();
var today = new Date();
//sample values
var sYyyy = Utilities.formatDate(new Date(rotDate), "GMT+8","yyyy");
var sMm = Utilities.formatDate(new Date(rotDate), "GMT+8","MM");
var sDd = Utilities.formatDate(new Date(rotDate), "GMT+8","dd");
//Test Values
var tYyyy = Utilities.formatDate(new Date(today), "GMT+8","yyyy");
var tMm = Utilities.formatDate(new Date(today), "GMT+8","MM");
var tDd = Utilities.formatDate(new Date(today), "GMT+8","dd");
//var rotDate = sheet.getRange("F6").getValue();
//var today = sheet.getRange("F1").getValue();
//var today = new Date().toLocaleDateString(); // Today's date, without time
var dumpCell = sheet.getRange("J3");
var dumpCell2 = sheet.getRange("J4");
var dumpCell3 = sheet.getRange("J5");
if (sYyyy + sMm + sDd == tYyyy + tMm + tDd) {
//if(rotDate===today) {
//dumpCell is there to dump a value in a cell if the IF statement is true
dumpCell.setValue(rotDate);
MailApp.sendEmail("tv18766#gmail.com", "subject", "body");
}
//these dump the compared vars into cells so they can be checked against one another manually
dumpCell2.setValue(rotDate)
dumpCell3.setValue(today)
}

Doing Math with Date Values

I am trying to use the difference between two dates in my Google Sheet to determine the number of rows down that the originRange will be copied.
I'm getting an error 'Cannot convert NaN to (class)' so I'm assuming I need to change the format of the date in some part of the formula but I am completely stuck.
The dates in the Google Sheet are formatted "10/26/2016" & "12/31/2016" if that helps at all.
function fillNewReport () {
var startDate = responseSheet.getRange('C2');
var endDate = responseSheet.getRange('G2');
var dateDiff = (endDate - startDate) + 1;
var newReport = ss.getSheetByName('Copy of Form Responses 1');
var originRange = newReport.getRange(2,2,1,22);
var newRange = newReport.getRange(2,2,dateDiff,22);
originRange.copyTo(newRange);
}
Any help with this will be greatly appreciated.
Thank you,
EDIT: Part 2
I think I've got the right formatting now, as I'm no longer getting an error. But the formula is not responding. No rows are being copied. Any suggestions?
function fillNewReport () {
var startDateValue = responseSheet.getRange('C2').getValue();
var endDateValue = responseSheet.getRange('G2').getValue();
var startDateMilli = new Date(startDateValue);
var endDateMilli = new Date(endDateValue);
var startDate = startDateMilli.getDate();
var endDate = endDateMilli.getDate();
var dateDiff = (endDate - startDate) + 1;
var newReport = ss.getSheetByName('Copy of Form Responses 1');
var originRange = newReport.getRange(2,2,1,22);
var newRange = newReport.getRange(2,2,dateDiff,22);
originRange.copyTo(newRange);
}
In your code startDate and endDate are ranges, not values !
So first thing is to change that using getValue().
You will then get date objects that wont behave as you expect because unlike days in spreadsheets javascript date objects are more complex objects, they have date and time properties and have a native value of the number of milliseconds since the reference date...
Anyway, all you have to do is using the date methods described in all javascript reference on the internet, ask Google for "JS DATE"
Then do the math you need, this part will be easy I think.
edit
As I wrote in the comments, I'm not sure I understand what result you want to get...
I tried a test changing a few details and I get a result... you tell me if that's what you wanted.
function fillNewReport () {
var startDateValue = responseSheet.getRange('C2').getValue();
var endDateValue = responseSheet.getRange('G2').getValue();
var startDateMilli = new Date(startDateValue);
var endDateMilli = new Date(endDateValue);
Logger.log('startDateMilli = '+startDateMilli+' endDateMilli = '+endDateMilli);
var startDate = startDateMilli.getDate();
var endDate = endDateMilli.getDate();
var dateDiff = (endDate - startDate) + 1;
Logger.log('dateDiff = '+dateDiff);
var newReport = ss.getSheetByName('Copy of Form Responses 1');
var originRange = newReport.getRange(2,2,1,22);
var newRange = newReport.getRange(2,2,dateDiff,22);
originRange.copyTo(newRange);
}
or like this to copy only one row
...
var originValues = newReport.getRange(2,2,1,22).getValues();
Logger.log('originValues = '+originValues);
var newRange = newReport.getRange(2+dateDiff,2,1,22); // copies to the other sheet but dateDiff rows underneath...
newRange.setValues(originValues);
}

Set Value in Date format in first Empty Column : Google Script

I have a column in which dates are saved in string format like this: "Tuesday, 18th November(11:00)"
I want to take this string date and save its equivalent date in Date format corresponding to its row in new column (first empty column in sheet), so that I can later compare that date with current date.
I have written this function and I am in test phase. However I have two questions :
1) This function is not inserting value in corresponding row in new column.
2) Since setValue is Object type it will not save value in Date type, for me setDay, set Month methods are not working (may be because of wrong object).
Here is my code:
function replaceStringDate(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var lastRow = SpreadsheetApp.getActiveSheet().getLastRow();
var lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn();
var dataRange = sheet.getRange(startRow,2,lastRow,12);
var values = dataRange.getValues();
var index = dataRange.getRowIndex();
for(i=0;i<values.length;++i){
var lastCell = sheet.getRange(index,14);
var appointmentDateFirst = values[i][8] ;
if (appointmentDateFirst == "Thursday, 18th November (11:00 to 12:00)") {lastCell.setValue('18/11/2011');}
index=index+1;
} //end for loop
} //end function
here is a piece of code to start with, I played with string manipulation and regex... It's kind of fragile and needs to be improved to handle different cases but the idea is working...
I'm sure it can be done more efficiently with only regex but this string approach was easier...
function convertToDateTest(){
Logger.log(convertToDate("Tuesday, 18th November(11:00)"))
}
function convertToDate(str){
Logger.log(str.substring(str.indexOf(', ')+1,str.indexOf('(')).replace('th','')+' '+new Date().getFullYear());
var date = new Date(str.substring(str.indexOf(', '),str.indexOf('(')).replace('th','')+' '+new Date().getFullYear());
var time = str.match(/((([0-1]?[0-9])|([2][0-3])):)([0-5][0-9])/g);
Logger.log(time);
new Date(date).setHours(time[0]);
return date;
}