getMonth function cannot be found - google-apps-script

I am trying to get a sheet to populate data in a new tab, I need three columns type, service and date/month. However, the getMonth statement keeps throwing an error and I'm unsure why?
var service = inputSheet.getRange('O' + lastRow).getValue();
var date = inputSheet.getRange('L' + lastRow).getValue();
var month = date.getMonth();
I expected this to return the date held in variable date as the month it was entered.

You have to explicitly create a JavaScript / Google Apps Script Date object using the value returned by getValue():
var date = new Date(inputSheet.getRange('L' + lastRow).getValue());
var month = date.getMonth();
Note: getMonth() returns a value 0 - 11 not 1 - 12.

Related

day and month are swapped?

I have a column 'C' containing dates and in that some cell values are having values like " Due on Date". I have written app script code that if a cell value contains "Due on" it will be copied to another column,else copied to different column.But on running I found that cells having "due on " on running the date and month are interchanged. for eg: if a cell contains "Due on 08/02/2022(dd/MM/yyyy)" is changed to "02/08/2022(MM/dd/yyyy)". Is there any method to retain the same date format.I have already done the date format methods in the spreadsheet and maintained the same time zone .
Here is the sample code:
for(var i=value.length-1;i>=0;i--){
var chn = value[i];
if(chn[2]!="NA"){
// var rdate= new Date(chn[2]);
var dat=Utilities.formatDate(new Date(chn[2]), "GMT+5:30", "dd-MMMM-yyyy");
var mat= chn[2].toString();
if(mat.match(/Due on/)){
var d1= mat.replace("Due on", "");
var ds = new Date(dat);
var year = ds.getFullYear();
var month = ds.getDate();
var day = ds.getMonth();
Logger.log(chn[2]);
Logger.log(dat);
Logger.log(ds);
Logger.log(month);
// var pubdate = new Date(year, day,month);
// Logger.log(pubdate);
ss.getRange("C"+(i+2)).setValue("Valid till "+Utilities.formatDate(ds, "GMT+5:30", "dd-MMMM-yyyy"));
}
else{
.................
}
}
A copy of the spreadsheet and the executions log is attached here:
Execution log:
You code works for me correctly, however here are some thoughts for troubleshooting
You do not specify into which sheet you want to write (I assume ss is SpreadsheetApp.getActiveSpreadsheet()). This is dangerous when your spreadsheet has several sheets. It's best to sue the method getSheetByName()
Reduce your code snippet to something simpler to reduce potential error sources
Change you spreadsheet locale for changing the date formatting
Since your date is concatenated to a string (and the method formatDate() returns a date anyway), the output should not be affected by any locales and date formatting, however to be sure, try to set it explicitly to a string.
Make sure you pass to new Date() a valid date object or date string.
This code snippet works for me regardless of the spreadsheet locale and the number formatting of the cells:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
for(var i = 10; i >= 0; i--){
var dat=Utilities.formatDate(new Date("2022-05-15"), "GMT+5:30", "dd-MMMM-yyyy");
ss.getRange("C"+(i+2)).setValue(("Due on " + dat).toString());
}
}
UPDATE:
If the problem is the format of the original date string, you need to convert it to the necessary format for new Date(). To do so, you need to know the formatting of the original date string.
For a date string with the format ddmmyyyy , you can do it as following:
var chn = [];
chn[2] = "15052022";
var day = Number(chn[2].substring(0,2));
var month = Number(chn[2].substring(2,4));
var year = Number(chn[2].substring(4,8));
console.log("day: " + day)
console.log("month: " + month)
console.log("year: " + year)
var dat= Utilities.formatDate(new Date(year, month - 1, day), "GMT+5:30", "dd-MMMM-yyyy");
ss.getRange("C2").setValue(("Due on " + dat).toString());

Google App Script - How to subtract 7 days from a cell value thats assigned to a variable?

I have a script that checks each cell in a specific column, then gets me the value and stores it to a variable. The cells in that column all have different dates in this format. 9/9/2020
I'm trying to figure out how to create another variable that subtracts 7 days from the given date.
Can someone help me with creating a variable that subtracts 7 days from the date grabbed by the "start_date" variable.
Example:
var sss = SpreadsheetApp.openById('1rIK-TunX1lBlFzndk5L4ExdLQO1GQLwlH-1viZzFZU0');
var ss = sss.getSheetByName('Form Responses 1');
function test() {
var lr = ss.getLastRow()
for (var i = 2;i<=lr;i++){
var start_date = ss.getRange(i,13).getValue();
var minus7days = ??
}}
Any help would be greatly appreciated!!
Working with date objects
When performing calculations with date objects, the best is to convert them to milliseconds.
This can be done e.g. with getTime()
After the calculation you can transform the milliseconds back to a date object with new Date()
Sample Code snippet:
var ms = start_date.getTime();
var sevenDays = 7*24*60*60*1000;
var minus7daysMs = ms - sevenDays;
var minus7days = new Date(minus7daysMs);
Another way to do the same is through setDate, which sets the day of month:
//simulate getValue
const start_date = new Date("2020-9-9");
const minus7date = new Date(start_date);
minus7date.setDate(start_date.getDate()-7);
console.info({start_date,minus7date});

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.

Google script -- adding days to a date

I realize this is likely very easy but I'm a struggling newbie. I have dates in spreadsheet cells D3, D4, and D5 (mm/dd/yyyy) and simply need a macro to add 7 days to each of them. I've managed to mangle together some code that may be working but the output is in milliseconds rather than mm/dd/yyyy format.
I can't seem to get the syntax right to convert it. Any hints? Thank you!
function UpdateDates() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var First = new Date();
var Second = new Date();
var Third = new Date();
var First = ss.getRange('D3').getValue();
var Second = ss.getRange('D4').getValue();
var Third = ss.getRange('D5').getValue();
ss.getRange('D3').setValue(First.getTime() + 7);
ss.getRange('D4').setValue(Second.getTime() + 7);
ss.getRange('D5').setValue(Third.getTime() + 7);
}
Adding days to date provides a unique challenge mainly because you have to take care of year, month and date. And increment each accordingly, hence just using getDate() doesn't work. You will need to keep track of the month and year. So as to change them if adding the seven days change the month or the year.
However, by using getTime() you can get the measure of time in milliseconds since Jan 1, 1970. And, add 7 days in milliseconds and convert it back to a date using new Date() constructor. Thus the constructor would take of figuring out the correct date based on the time.
Your code will look like so:
function UpdateDates() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Get the dates from the cell and convert them into Milliseconds since 1970/01/01
var First = new Date(ss.getRange('D3').getValue()).getTime();
var Second = new Date(ss.getRange('D4').getValue()).getTime()
var Third = new Date(ss.getRange('D5').getValue()).getTime();
var dayInMs = 24*60*60*1000 //one day in Milliseconds
//add sevendays to each date in milliseconds
First = First + (7*dayInMs)
Second += (7*dayInMs)
Third += (7*dayInMs)
//Convert Milliseconds to date use new Date(time in ms) and set Values of the cell
ss.getRange('D3').setValue(new Date(First));
ss.getRange('D4').setValue(new Date(Second));
ss.getRange('D5').setValue(new Date(Third));
}

"Row Last Modified" Script Produces Wrong Month

This code has been working well for me, but today (when I modified a cell) I noticed that the script is producing a date that is one month behind the actual date (i.e., today is 6/5/2013, but the script produced 5/5/2013). Can anyone see what might be causing this problem?
// * based on the script "insert last modified date" by blisterpeanuts#gmail.com *
// Update cell with the the last modified time of any (single) cell in that row, excluding row 1 and column 1
function onEdit() {
var d = new Date();
// format date nicely
var month_str = d.getMonth();
var day_str = d.getUTCDate();
var year_str = d.getYear().toString().substring(2);
// create the formatted time and date strings
var date_str = month_str + '/' + day_str + '/' + year_str;
// create the message (change this to whatever wording you prefer)
// note also that rather than all the above, you could just use d.toString()
// I didn't because I didn't want it printing the timezone.
var s = date_str;
var active_range = SpreadsheetApp.getActiveRange();
if (active_range.getHeight() == 1 && active_range.getWidth() == 1 && active_range.getRow != 1 && active_range.getColumn() != 1) {
var update_row = active_range.getRow().toString();
var update_cell = "AF" + update_row;
SpreadsheetApp.getActiveSheet().getRange(update_cell).setValue(s);
}
}
I don't think this has ever worked correctly for you. The documentation for Date.getMonth() says:
The value returned by getMonth is an integer between 0 and 11. 0
corresponds to January, 1 to February, and so on.
You need to increment the month by one.
var month_str = d.getMonth() + 1;
(Also the variable name month_str is misleading, it isn't a string, getMonth() returns an integer)