Converting timestamps to dates in Google sheet script - javascript

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);
}

Related

Auto Move Data of Specific Date

Link of My sheet is :
https://docs.google.com/spreadsheets/d/1czJbRU5ELNft1IfGq1cABGe30j8BWjnffVCEa8A_AeY/edit?usp=sharing
I am trying to move data if N is equal to today. I have set the trigger. This script runs on time driven between 8 PM to 9 PM. It copies the data in Row 8 when column K onwards there is noting mentioned. In the current Payment Approval Sheet, while running the script it copies the data in 1500th row.
The script I am using is as below:
function copyrange() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Complete Invoice Sheet'); //source sheet
var testrange = sheet.getRange('N:N');
var testvalue = (testrange.setNumberFormat("#").getValues());
var ds = ss.getSheetByName('Payment Approval Sheet'); //destination sheet
var data = [];
var j =[];
var dt = new Date();
var today = Utilities.formatDate(new Date(), 'GMT-0', 'dd/MM/yyyy')
//Condition to check in N:N, if true, copy the same row to data array
for (i=0;i<testvalue.length;i++) {
if (testvalue[i] == today) {
data.push.apply(data,sheet.getRange(i+1,1,1,13).getValues());
//Copy matched ROW numbers to j
j.push(i);
}
}
//Copy data array to destination sheet
ds.getRange(ds.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}
Issue:
Your current solution considers the last row of your destination
sheet Payment Approval Sheet. However, in that sheet, checkboxes
are populated in column N until the bottom of the sheet. Therefore,
getLastRow() returns the row at the bottom of column N which is not
what you want.
Explanation:
Instead of using getLastRow(), calculate the number of elements after cell A7 by using the filter() operation and then use this as a starting point when you copy & paste the data to the destination sheet:
var start_row=ds.getRange('A8:A').getValues().filter(String).length +7; //calculate max row
ds.getRange(start_row+1,1,data.length,data[0].length).setValues(data);
Solution:
function copyrange() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Complete Invoice Sheet'); //source sheet
var testrange = sheet.getRange('K:K');
var testvalue = (testrange.setNumberFormat("#").getValues());
Logger.log(testvalue);
var ds = ss.getSheetByName('Payment Approval Sheet'); //destination sheet
var data = [];
var j =[];
var dt = new Date();
var today = Utilities.formatDate(new Date(), 'GMT-0', 'dd/MM/yyyy')
//Condition to check in N:N, if true, copy the same row to data array
for (i=0;i<testvalue.length;i++) {
if (testvalue[i] == today) {
data.push.apply(data,sheet.getRange(i+1,1,1,13).getValues());
//Copy matched ROW numbers to j
j.push(i);
}
}
//Copy data array to destination sheet
var start_row=ds.getRange('A8:A').getValues().filter(String).length +7; //calculate max row
ds.getRange(start_row+1,1,data.length,data[0].length).setValues(data);
}

Dates manipulation between Spreadsheet and Arrays

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
}

Delete cells in range if less than current date

I have a range of dates in plain text format (must stay this way) and I need to clear them at 1am if the date in each range cell is less than the current date. I can set up the run schedule later, but can anyone tell me why this isn't working?
I'm using =TEXT(TODAY(),"m/dd") to insert the current date in the correct format in cell AE3.
Thank you!
function clearOldDate()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Loads");
var cells = sheet.getRange('AC9:AE33').getValues();
var data = [cells];
var date = sheet.getRange('AE3').getValues();
//var Sdate = Utilities.formatDate(date,'GMT+0900','MM/dd');
for(i=0; i<76; i++)
{
if (date > data[i])
{
data[i].clear();
};
};
};
This should do the trick
function clearOldDate()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("LogSheet");
//getValues gives a 2D array.
var data = sheet.getRange('AC9:AE33').getValues();
var date = sheet.getRange('AE3').getValues();
//var Sdate = Utilities.formatDate(date,'GMT+0900','MM/dd');
//This for loop with loop through each row
for(i=0; i<data.length; i++)
{
//This for loop with loop through each column
for (var j = 0; j < data[i].length ; j ++){
//This assumes Column AC has the dates you are comparing aganist
if (date > data[i][j])
{
//sets that the Row with index i to empty
data[i] = ["","",""]
};
}
};
//finally set the value back into sheet
sheet.getRange('AC9:AE33').setValues(data)
};
Basically, you need to setValues once data array is modified.
Note: This Statement (date > data[i][0]) doesn't work as expected when the values are stored as text.
Edit: Modified the code and added a new for loop to go through each column, based on comments

Google Sheets - Delete Expired Rows Based On Date

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

Trouble with a simple GoogleScript code (google sheets + gmail integration)

function checkReminder() {
// get the spreadsheet object
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// set the first sheet as active
SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]);
// fetch this sheet
var sheet = spreadsheet.getActiveSheet();
// figure out what the last row is
var lastRow = sheet.getLastRow();
// the rows are indexed starting at 1, and the first row
// is the headers, so start with row 2
var startRow = 2;
// grab column 10 (the 'date end' column)
var range = sheet.getRange(2,10,lastRow-startRow+1,1 );
var numRows = range.getNumRows();
var date_end_values = range.getValues();
// Now, grab the Event name data
range = sheet.getRange(2, 5, lastRow-startRow+1, 1);
var reminder_info_values = range.getValues();
var warning_count = 0;
var msg = "Send out a follow-up email asking how the event was!";
}
//Get today's date
var todaysDate = new Date();
var numRows = numRows
// Loop over the days left values
for (var i = 0; i <= numRows - 1; i++) {
var date_end = date_end_values[i][0];
//call setHours to take the time out of the comparison
if(date_end == todaysDate.setHours(0,0,0,0)) {
MailApp.sendEmail("max#xpogo.com",
"Reminder Spreadsheet Message", msg);
}
What I'm trying to do is have gmail send me a reminder when a certain column in my data set is equal to the present date. Im new to coding and am running into trouble. Please help?
I added the following after your variables were set, to determine whether they were commensurate for your comparison (hit ctrl+Enter after executing to view the log).
Logger.log(date_end);
Logger.log(todaysDate.setHours(0,0,0,0));
They weren't comparable at all. Here are the lines I changed to make this work:
var todaysDate = Utilities.formatDate(new Date(), "GMT+1", "MM/dd/yyyy");
var date_end = Utilities.formatDate(date_end_values[i][0], "GMT+1", "MM/dd/yyyy");
if(date_end == todaysDate) {
HTH

Categories