I have a google spreadsheet where some of the sheets names are text and others are dates in "dd/mm/yyyy/" format. I need a function that can put the sheet called "Tablero" first, then sort the sheets named with dates descendingly, and leave at the end the rest of the sheets.
This is my code so far:
function testOrdenar() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetsCount = ss.getNumSheets();
var sheets = ss.getSheets();
// I need the sheet "Tablero" to go first
var tablero = ss.getSheetByName("Tablero");
ss.setActiveSheet(tablero);
ss.moveActiveSheet(1);
var names = []; // This is where the sheets named with dates will go
var j = 1; // I use this as a counter, but it is not absolutly necessary
for (var i = 0; i<sheetsCount; i++){
var sheetName = sheets[i].getName();
var pattern = /(\d{2})\/(\d{2})\/(\d{4})/;
var dt = new Date(sheetName.replace(pattern,'$3-$2-$1'));
if (dt instanceof Date && !isNaN(dt.valueOf())) {names[j] = dt; j++;} // This is to distinguish the sheets that are dates
}
// Here I sort the sheets descendingly
for (var m = 1;m<j;m++) {
for (var n = 1;n<j;n++) {
if (names[n] < names[m]) {
var aux = names[n];
names[n] = names[m];
names[m] = aux;
}
}
}
var pos = 2;
for (var a = 0;a<j;a++) {
var sheetName = Utilities.formatDate(new Date(names[a]), "GMT-3", "dd/MM/yyyy");
Logger.log(sheetName);
var sheet = ss.getSheetByName(sheetName);
ss.setActiveSheet(sheet);
ss.moveActiveSheet(pos);
pos++;
}
The sorting is correct, but I don't know why each date ends up being a day less. I tried adding one to de variable but it comes out as "Invalid Object". And I also need those dates as strings because that is how i can then call the sheets.
My questions:
1) How can I get the correct dates? (not a day before each one). Could it have something to do with the timezone? I'm in "GMT-3".
(If the answer is adding one, please tell me how because I tried that and comes back as an error.)
2) How can I get the sorted dates as strings in "dd/MM/yyyy" format?
Here are the screenshots of my sheets and the logs I get:
Cause:
As written in the documentation, Date.parse(timestring), where timestring is a date only iso8601 compatible string, returns a date in UTC. When you format the date in GMT-3, the date is offset 3 hours to the previous day.
Solution:
Use GMT as timezone argument of Utilities.formatDate
Alternatively, You can avoid converting to date at all and sort them as plain strings.
Sample script:
function testOrdenar1() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheets = ss.getSheets();
const pattern = /(?:Tablero)|(\d{2})\/(\d{2})\/(\d{4})/;
const map = sheets.reduce( //Create a map of sheet object : sheetName(as yyyyMMdd)
(m, sheet) =>
m.set(
sheet,
sheet
.getName()
.replace(pattern, (m, p1, p2, p3) =>
m === 'Tablero' ? '99999999' : p3 + p2 + p1//make Tablero highest 8 digit number string
)
),
new Map()
);
sheets.sort((a, b) => map.get(b) - map.get(a));//sort sheet objects by their name
let pos = 1;
sheets.forEach(sh => {
ss.setActiveSheet(sh);
ss.moveActiveSheet(pos++);
});
}
Related
I have a script that runs in a google sheet that parses emails and creates new lines in the sheet. This is used to create a log file from periodically emailed log updates. This works very well.
Currently, I have a variable that is used to determine which emails are ingested based on the month (0=January, etc.)
That variable has to be adjusted every month and then I have to create a new monthly sheet (tab in the main) and do a bunch of sorting and moving emails in gmail.
I'd like to set this up so it automatically puts the January emails in a sheet for January and the February emails in a sheet for February.
I thought about cascading if elseif statements, but that got too unwieldy fast.
I thought about iterating using a for loop through an array holding all emails, but that seems convoluted too.
Any suggestions?
::EDIT::
To be clear, I'm really interested in how to parse all of the emails and send the ones from January to the January sheet (for example).
::EDIT:: Added current script
function myFunction() {
var label = GmailApp.getUserLabelByName(myLabel);
var label2 = GmailApp.getUserLabelByName(newLabel);
var threads = label.getThreads();
var data = new Array();
var newData = new Array();
// get all the email threads matching myLabel
for (var i = 0; i < threads.length; i++) {
var messages = GmailApp.getMessagesForThread(threads[i]);
// archive thread
label2.addToThread(threads[i]);
label.removeFromThread(threads[i]);
// get each individual email from the threads
for (var j = 0; j < messages.length; j++) {
var bodyText = messages[j].getPlainBody();
// split the email body into individual "paragraph" strings based on the regExp variable
while (matches = regExp.exec(bodyText)) {
var logdata = matches[1];
for (k in keys) {
logdata = logdata.replace(keys[k], "");
}
// split out each "paragraph" string into an array
var lines = logdata.split(/[\r\n]+/);
for (l in lines) {
lines[l] = lines[l].replace('*F','');
lines[l] = lines[l].trim();
}
for (l in lines) {
lines[l] = lines[l].replace(/^(\:\s)/, "");
}
// Turn the first element in the array into a date element, format it, and put it back
lines[0] = Utilities.formatDate(new Date(lines[0]), "America/Phoenix", "M/d/yy HH:mm:ss");
// Put the array to a new item in the data array for further processing
if (curMonth == (new Date(lines[0]).getMonth())) {
data.push(lines);
}
}
}
}
// Compare the information in the data array to oldData information in the sheet
if (data.length) {
var oldData = s.getRange(range).getValues();
for (h in oldData) {
oldData[h][0] = Utilities.formatDate(new Date(oldData[h][0]), "America/Phoenix", "M/d/yy HH:mm:ss");
}
for (i in data) {
var row = data[i];
var duplicate = false;
for (j in oldData) {
if (row.join() == oldData[j].join()) {
duplicate = true;
}
}
if (!duplicate) {
newData.push(row);
}
}
// check to write newData only if there is newData, this stops an error when newData is empty
if (newData.length) {
s.getRange(s.getLastRow() + 1, 1, newData.length, newData[0].length).setValues(newData);
}
s.getRange(range).sort(1); //sorts the sheet
}
}
Try this:
function getSheet(date) {
var ss=SpreadsheetApp.openById('SpreadsheetId');
var name=Utilities.formatDate(new Date(date), Session.getScriptTimeZone(), "MMMyyyy")
var sh=ss.getSheetByName(name);
if(!sh) {
var sh=ss.insertSheet(name);
}
return sh;
}
I ended up basing my solution on the solution that #cooper provided, but had to go a little further.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var month = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var curMonth = new Date().getMonth(); //number of month -1 aka: January = 0
var sheetname = month[curMonth] + " " + new Date().getYear();
var s = ss.getSheetByName(sheetname);
function newMonth(){
if (!s) {
var template = ss.getSheetByName('Template').copyTo(ss);
template.setName(sheetname);
s = ss.getSheetByName(sheetname); //"reload" the sheet
s.showSheet(); //unhide the new copy since 'Template' is hidden in the spreadsheet
ss.setActiveSheet(s); //make it active
ss.moveActiveSheet(0); //move it to the first position
}
}
I am writing a code that targets a column with dates and I would like to get the dates and compare it to the current date so that I can get the difference between the two.
I ran into a problem I am having trouble solving. It seems that when I used .getValues in my range, it placed each timestamp in an array then those arrays in another array. Like this: [[(new Date(1539619200000))], [(new Date(1540396800000))], [(new Date(1540828800000))]]
I would like to place all the values in 1 array only so I can start solving how to convert the timestamps in to normal dates. I am also a beginner with this so I am sorry if this seems like an basic question.
function datesincolumn() //collects only the date values in range
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow(); //will identify last row with any data
entered
var range = sheet.getRange('D2:D' + lastRow); //will get range of cells
with data present
var dates = range.getValues();//gets all values in the range
var CurrentDate = new Date();
var timestamps = [];
for (i = 0; i <= dates.length; i++)
{
if (dates[i] >= i)
{
timestamps.push(dates[i]);
}
}
Logger.log(dates);
}
When you use .getValues(), you will always get a 2-dimensional array. The outer array represents the row, and the inner array represents the columns. Since you're only getting one column, you can simply append [0] to your dates[i].
function datesincolumn() { //collects only the date values in range
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow(); //will identify last row with any data entered
var range = sheet.getRange('D2:D' + lastRow); //will get range of cells with data present
var dates = range.getValues();//gets all values in the range
var CurrentDate = new Date();
var timestamps = [];
for (var i = 0; i <= dates.length; i++) {
var date = dates[i][0];
if (date >= i)
timestamps.push(date);
}
Logger.log(dates);
}
I'm trying to make a function to look over a list of days (a year school calendar), and, compare with a date from a user prompt and, until the date (all the days "lower" than the user date) set in the B column a string (in this case "Summer holidays", only if there's not another value in the B column corresponding to cell.
What I have:
What I expect, if I set Sept 12th in the input:
function setTrimesters() {
var sheet =
SpreadsheetApp.getActive().getSheetByName("calendar2017");
// Start of 1st trimester
var input = ui.prompt("Set first day of trimester (DD/MM)");
var value = input.getResponseText();
var allStartEndTrimesters = [valorInici1rTri]
// Get dataRange
var dataRange = sheet.getRange('A1:B'+sheet.getLastRow());
// Get dataRange values
var data = dataRange.getDisplayValues();
for (var i = 0 ; i < data.length ; i++) {
if (data[i][0] < value) {
if (data[i][1] == '') {
data[i][1] = "Summer holidays";
}
}
}
dataRange.setValues(data);
}
The script is working only with the day value of the date. Then, in October, from 1st to 11th the script assign too the value "Summer holidays".
I don't know how to get day and month values before comparing. I've tried to setNumberFormat to miliseconds, or days (similar to 42895 or so)... but there are some limitations with SpreadsheetApp and App Scripts working with dates.
Thanks in advance for helping
The problem is that you work with dates as strings, so they get compared in lexicographic order. With day being first, 4/9 precedes 5/7, which is not what you wanted. I suggest to
Use getValues instead of getDisplayValues. It will retrieve JavaScript date object instead of a string. Then the comparison < works correctly, but you also need the beginning date to be a Date object: see below.
Do not overwrite input data in column A. Separate input and output ranges.
Here is an example, with user-interface part removed:
function testSummer() {
var sheet = SpreadsheetApp.getActiveSheet();
var userEnteredDate = "26/07"; // what you get from user
var dateParts = userEnteredDate.split("/");
var beginning = new Date();
beginning.setMonth(dateParts[1] - 1, dateParts[0]);
beginning.setHours(0, 0, 0, 0); // so it's 0 hour of the day entered, in the current year
var inputData = sheet.getRange('A1:A'+sheet.getLastRow()).getValues();
var outputRange = sheet.getRange('B1:B'+sheet.getLastRow());
var outputData = outputRange.getValues();
for (var i = 0; i < inputData.length; i++) {
if (inputData[i][0] < beginning && outputData[i][0] == "") {
outputData[i][0] = "summer vacation";
}
}
outputRange.setValues(outputData); // not overwriting input
}
I'm currently trying to make a script or literally anything that will be able to delete a row after the given date in Column C.
The site is a giveaway site so I need the rows/entries to delete themselves once the date specified on Column C is passed.
Eg: If one giveaway had an expiration date # 20/13/2016, once the date reaches this date of 20/13/2016 it will delete the row. I am following the metric system of dd/mm/yy as a note.
I saw a question similar to this at Google Sheets - Script to delete date expired rows but the code won't work for my needs.
Here is the code that was used in the other question.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Foglio1");
var datarange = sheet.getDataRange();
var lastrow = datarange.getLastRow();
var values = datarange.getValues();// get all data in a 2D array
var currentDate = new Date();
var oneweekago = new Date();
oneweekago.setDate(currentDate.getDate() - 7);
for (i=lastrow;i>=2;i--) {
var tempdate = values[i-1][2];// arrays are 0 indexed so row1 = values[0] and col3 = [2]
if(tempdate < oneweekago)
{
sheet.deleteRow(i);
}
}
}
If you could change it to work for my above needs it will be greatly appreciated!
Assuming your dates are in column C as stated, this should do it. The adjustment is just to the date to which we compare and to handle missing dates. I am also messing with the case on some names for readability.
function DeleteOldEntries() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Live Events");//assumes Live Events 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 currentDate = new Date();//today
for (i=lastrow;i>=3;i--) {
var tempDate = values[i-1][2];// arrays are 0 indexed so row1 = values[0] and col3 = [2]
if ((tempDate!=NaN) && (tempDate <= currentDate))
{
sheet.deleteRow(i);
}//closes if
}//closes for loop
}//closes function
I have looked at various solutions posted i.e. parsing, substrings and splitting and none of them either produce a value or the required value.
The format received via Salesforce API is "2014-08-19T02:26:00.000+0000"
Essentially I would like a custom function that can be used within Google Sheets to convert this date/time format and take daylight saving into consideration
Thank you beforehand
I use a simple function like below :
function parseDate(string) {
var parts = string.split('T');
parts[0] = parts[0].replace(/-/g, '/');
var t = parts[1].split(':');
var refStr = new Date(new Date(parts[0])).toString();// use this to get TZ for daylight savings
var fus = Number(refStr.substr(refStr.indexOf('GMT')+4,2));
return new Date(new Date(parts[0]).setHours(+t[0]+fus,+t[1],0));
}
firstly thank you for everyone's input. By using a combination of the info provided by RobG and Serge insas I revised the script and created one that suited my needs. Please see below, any further advice would be welcome.
/*
The script first has all variables declared.
As the script runs inconjunction with an API query running off single trigger for defined sequential functions where the previous parsed date records are cleared and then re-parsed and runs with loop function for a whole column of data within specified range
*/
function parseDate() {
var source_spreadsheet = SpreadsheetApp.openById("Sheet_Id");
SpreadsheetApp.setActiveSpreadsheet(source_spreadsheet);
var sheet = source_spreadsheet.getSheetByName("Sheet_Tab");
var startRow = 2;
var numRows = 4500;
var startCol = 1;
var numCols = 7;
var dataRange = sheet.getRange(startRow, startCol, numRows, numCols)
sheet.getRange(startRow, startCol + 1, numRows, numCols - 1).clear({contentsOnly: true});
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var SFConnectDate = row[0];
var DConnected = row[1];
var SFCutoverDate = row[2];
var DInUse = row[3];
var Lat = row[5];
var Long = row[6];
if (SFConnectDate != "" && DConnected == "" && Lat != "" && Long != "") {
var parts = SFConnectDate.split('T');
parts[0] = parts[0].replace(/-/g, '/');
var Fdd = parts[0].split('/');
var AllTime = parts[1].split('.');
var Ftt = AllTime[0].split(':');
var D = new Date(Fdd[0],(Fdd[1]-1),Fdd[2] ,Ftt[0],Ftt[1],Ftt[2]);
var TZ = (D.getTimezoneOffset())/60;
var DConnected = new Date(Fdd[0],(Fdd[1]-1),Fdd[2],(Ftt[0]-TZ),Ftt[1],Ftt[2]);
sheet.getRange(startRow + i, 2).setValue(DConnected);
}
}
}