I have a column containing dates and in that some cell values are having values like " Due on Date". I have written a 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.Here is the sample code:
function addYear(ss){
var value = ss.getDataRange().getValues();
value.shift();
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(rdate), "GMT+5:30", "dd-MM-yyyy");
var mat= chn[2].toString();
if(mat.match(/Due on/)){
var d1= mat.toString().replace("Due on", "");
var ds = new Date(dat);
ss.getRange("C"+(i+2)).setValue("Valid till "+Utilities.formatDate(ds, "GMT+5:30", "dd-MMMM-yyyy"));
}
else{
var ds = new Date(chn[2]);
var yearadc = ds.getFullYear();
var monthadc = ds.getMonth();
var dayadc = ds.getDate();
var adc = new Date(yearadc + 1, monthadc, dayadc-1);
ss.getRange("C"+(i+2)).setValue("Valid till "+ Utilities.formatDate(adc, "GMT+5:30", "dd-MMMM-yyyy"));
}
}
I have made some changes to the code but if the day is greater than 12,the code reads as 01/01/1970. I am attaching a image relevant to this code.
I want to retain the original format as dd/MM/yyyy
Related
I am new to writing scripts and I was experimenting.
I want to add time stamp along with the string.
const sheet = SpreadsheetApp.openByUrl(SHEET_URL).getSheetByName(
SHEET_NAME
);
const [header] = sheet.getRange('A1:1').getValues();
const STATUS = header.indexOf('Status');
var rowId = Number(e.parameter.row);
var date = new Date()
sheet.getRange(rowId + 1, STATUS + 1).setValue("Data Sent- " + date);
however, all I am getting the Status Column is Data Sent- and no time stamp.
please help where am i going wrong.
Thanks in advance.
You should convert the date to a string first, like this:
var date = new Date();
var timezone = 'GMC';
var format= 'YYYY-mm-dd';
var formatted_date = Utilities.formatDate(date,timezone , format);
sheet.getRange(rowId + 1, STATUS + 1).setValue("Data Sent- " + formatted_date);
Reference: GAS Utilities Format Date
I am new to scripting, and have been trying to get a script to place a date in an adjacent cell when a checkbox is checked. This is a minor part of the whole script I am trying to get working. I am trying to write a script to build a new sheet from another sheets values, including naming the sheet.
I can get the script to work when I type the sheet name into the if statement, but when I try and use an argument by calling the sheet name and calling string, I can not get them to return a true value.
When I log the sheet name and the string they match. If I copy and paste ether value from the log into the sheet name it will then return true. It will also return true when I type the name of the sheet.
I have tried to change the type using: toString() but this has not worked.
I have tried to use the length and typeof to find the solution, from this page:
How to debug identical strings that do not equal in google app script?
But they where the same type and length. I have tried to get the every function on this page to work but have been unsuccessful in getting it to run.
I have used it like this:
[td].every((char,i) => char === nac[i] || console.info(`Unequal character at ${i}`))
and get this error:
10:55:03 AM Error
TypeError: Cannot read property 'every' of undefined
onEdit # Time Stamp test day.gs:33
Code:
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ac = ss.getActiveSheet();
var as = ss.getActiveSheet().getSheetName();
var d = new Date();
var month = new Array(12);
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apl";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var year = d.getFullYear();
var date = d.getDate();
var today = month[d.getMonth()] + " " + date +", " + year
var td = "Test " + today
var nac = ac.getSheetName()
Logger.log(td)
Logger.log(nac)
Logger.log(nac == td)
if(nac == td) {
var cell = ac.getActiveCell()
var col = cell.getColumn()
if(col == 9 && cell.getValue() == true){
Logger.log(123456)
var date = new Date()
var dateCell = cell.offset(0,1)
dateCell.setValue(date)
}//close if
} // Close if
} // Close function
Log
11:26:46 PM Notice Execution started
11:26:47 PM Info Test Dec 27, 2020
11:26:47 PM Info Test Dec 27, 2020
11:26:47 PM Info false
11:26:47 PM Notice Execution completed
I had this working using a listbox, but now I want to change it to a textbox and I keep getting the error: "Error encountered: Cannot read property "1" from undefined." I am not sure of the issue. I had this same code working with a listbox and just tweaked it. I am needing help to solve the problem and wondering if I am down the wrong path.
EDIT - ERROR OCCURANCE
The error occurs when I put in a Student ID Number on the form, that references a Google Spreadsheet. When I hit Enter, I get the error and nothing auto-fills the other fields I have setup.
Form Build (part)
//Create the form elements
//Set DateBox to Today's Date
var date = new Date()
var txtDate = app.createTextBox().setName("txtDate").setId("txtDate").setValue(Utilities.formatDate(date, 'America/New_York', 'MM/dd/yyyy | hh:mm a')).setReadOnly(true).setEnabled(false).setStyleAttributes(lockedStyle);
var lblStudentNumber = app.createLabel('Student ID#:');
var hdlStudentInfo = app.createServerHandler('getStudentInfo').addCallbackElement(vrtMainPanel);
var lbxStudentInfo = app.createTextBox().setId('lbxStudentInfo').setName('lbxStudentInfo').addChangeHandler(hdlStudentInfo).addChangeHandler(alertHideHandler);
// var txtStudentNumber = app.createTextBox().setName("txtStudentNumber").setId("txtStudentNumber").setReadOnly(false).setEnabled(true).setStyleAttributes(normalStyle);
var lblStudentName = app.createLabel('Student Name:');
var txtStudentName = app.createTextBox().setName("txtStudentName").setId("txtStudentName").setText("Student Name").setReadOnly(true).setEnabled(false).setStyleAttributes(lockedStyle);
getStudentInfo Function
function getStudentInfo(e){
var spSheet = SpreadsheetApp.openById('1OhR5i8B89uK7XXW2Izdzim0LSngSr6KQPqL5ToeZTbo');
var spStudentList = spSheet.getSheetByName('Schedule');
var lstStudentID = spStudentList.getRange(2,1,spStudentList.getLastRow(),18).getValues();
var app = UiApp.getActiveApplication();
// var currTime = new Date();
// var formattedTime = Utilities.formatDate(currTime,"hh:mm a");
var txtStudentName = app.getElementById('txtStudentName');
var txtTeacherName = app.getElementById('txtTeacherName');
// var txtExt = app.getElementById('txtExt');
var txtEmail = app.getElementById('txtEmail');
var txtPeriod = app.getElementById('txtPeriod');
var txtSubject = app.getElementById('txtSubject');
txtStudentName.setText(lstStudentID[e.parameter.lbxStudentInfo][1] + " " + lstStudentID[e.parameter.lbxStudentInfo][2]);// sets Student's Name
txtPeriod.setText("1st Period");// sets Period
txtSubject.setText(lstStudentID[e.parameter.lbxStudentInfo][6]);// sets Subject
txtTeacherName.setText(lstStudentID[e.parameter.lbxStudentInfo][7]);// sets Teacher's Name
txtEmail.setText(lstStudentID[e.parameter.lbxStudentInfo][8]);// sets Email
// txtExt.setText(lstStudentID[e.parameter.lbxStudentInfo][1]);// sets Ext
return app;
}
Problem:-
I need to get Name and ID of the latest created document from some Google Drive folders.
Solution:-
I wasn’t able to find an easy way to get it, hence, created a loop for files within the folder to get max date - then loop again in folder to match the date and Log the name and date – the below code (when commented as mentioned) works properly for the solution.
Instead of rewriting the whole code with just a different folder name, I tried creating a loop for folder name as well.
However app script goes into infinite loop giving out the Maximum execution time limit message.
Any help appreciated.
function Get_lastestdate() {
//Define Spreadsheet and sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("PEOPLE");
//comment from here to work properly
for (var i =1; i < 4; i++) {
if (i = 1) { var foldername = "Folder1"}
if (i = 2) { var foldername = "Folder2"}
if (i = 3) { var foldername = "Folder3"}
// till here
//Define folder and files
var folder = DocsList.getFolder(foldername); //set folder name in case commenting.
var lastfile = folder.getFiles();
//Make a blank array
var noofdaysarray = []
var yeararray = []
//Loop to get all No of days in a year & the year
for (var i in lastfile) {
noofdaysarray.push(Utilities.formatDate(lastfile[i].getDateCreated(),"GMT","D"));
yeararray.push(Utilities.formatDate(lastfile[i].getDateCreated(),"GMT","y"));
}
//Get the max date from date and year
var largestdate = Math.max.apply(Math, noofdaysarray);
var largestyear = Math.max.apply(Math, yeararray);
//Get maximum available date
var matchcriteria = largestdate + largestyear
//Again loop for matching criteria with the actual date uploaded
for (var i in lastfile) {
var lastdate = Utilities.formatDate(lastfile[i].getDateCreated(),"GMT","D");
var lastyear = Utilities.formatDate(lastfile[i].getDateCreated(),"GMT","y");
var wholedate = parseInt(lastdate) + parseInt(lastyear); //parseInt is for converting text to number
//Get doc name if both dates matches
if (wholedate == matchcriteria) {
Logger.log(lastfile[i].getId());
Logger.log(lastfile[i].getName());
}
}
} //comment this as a part of loop
}
Between:- If there's an easier way to do it, please let me know.
You can use DocsList to retrieve the last modified files. you told that you want the last created but maybe the last modified can be usefull. Check the code bellow:
function findLastModified() {
//Retrieve folder
var folder = DocsList.getFolderById("0B0kQD4hSd4KASUJKb2cya0NET1U");
//Ask for 5 files
var numberOfFiles = 5;
//The first parameter is the search query, in this case we want all files
var filesResult = folder.findForPaging("", 5);
//By Default they will be sorted by last modified date
var files = filesResult.getFiles();
Logger.log("Found "+files.length+" files");
//Iterate
for(var x in files) {
var file = files[x];
Logger.log(file.getLastUpdated());
}
}
Live version here.
Dont use "i" in both inner and outer loops. that will be a problem.
wouldn't it be easier to do something like this so you only do one loop?
var mostRecentDate = new Date(2000,01,01);
var fileName="";
var fileId="";
for(var i = 1; i<5; i++){
var folder = DocsList.getFolder('Folder'+i);
var files = folder.getFiles();
for(var j in files) {
if(files[j].getDateCreated()>mostRecentDate){ //or getLastUpdated
mostRecentDate=files[j].getDateCreated();
fileName=files[j].getName();
fileId=files[j].getId();
}
}
}
Logger.log("File: " + filename + " Id: " + fileId + " Created: " + mostRecentDate);
You may need to do paging if you have a huge number of files & folders to iterate through.
I have created a Ui on a Google Sites page with a date field (date picker). Is there a way to pre-populate it with the current date? Secondly, is there a way of isolating the year from the date picked? Here is the code I have so far:
//Create elements for vPanel_01
var labelDate = app.createLabel("Date of event:");
var textBoxDate = app.createDateBox().setName("date").setStyleAttribute("color", "#a7a7a7");
I'd like to isolate the year from the input so that I can use for comparisons in the script.
Is there a way to pre-populate it with the current date?
The following code does the required.
var now = new Date();
var labelDate = app.createLabel("Date of event:");
var textBoxDate = app.createDateBox().setName("date").setStyleAttribute("color", "#a7a7a7").setValue(now);
is there a way of isolating the year from the date picked?
Please explain what do you expect to have by writing isolating the year from the date picked? Do you need to extract a year of a date? If yes, the the following does it.
function doGet(e) {
var app = UiApp.createApplication();
var now = new Date();
app.add(app.createLabel('Current Year: ' + now.getFullYear()));
return app;
}
The code which extracts year from a date box.
function doGet(e) {
var app = UiApp.createApplication();
var now = new Date();
var dateBox = app.createDateBox().setName('datebox').setValue(now);
var label = app.createLabel(now).setId('label');
var handler = app.createServerHandler('onBtnClick');
handler.addCallbackElement(dateBox);
var btn = app.createButton('Click Me').addClickHandler(handler);
app.add(dateBox);
app.add(label);
app.add(btn);
return app;
}
function onBtnClick(e) {
var selectedDate = new Date(e.parameter.datebox);
var year = selectedDate.getFullYear();
var app = UiApp.getActiveApplication();
var label = app.getElementById('label');
label.setText('Selected Date: ' + selectedDate + ', Year: ' + year);
return app;
}
Following your comment : if I keep megabytes1024's example you should add an handler to the textBox (or to a button hat validates the input) and a callBackElement to this handler and then, in the handler function you can use something like this :
var dateObject = new Date(e.parameter.date); // 'date' is the name of the datepicker
When you have this date object you can get whatever you want from it, for example :
var fullyear = dateObject.getFullYear(); // will return full year in 4 digits
see doc on date object
You could be interested in this example as well.