Join Date and time for events from sheet to calendar [duplicate] - google-apps-script

This question already has an answer here:
Google Apps Script: Concatenating date and time
(1 answer)
Closed 10 months ago.
With this code I can send the events directly to google calendar from google sheets. The start date and end date are on two different columns (col D and col F), the problem is that I need also the time that are on others two columns (col E and col G).
How could I join startDate with date+time and endDate with date+time?
function sendToCalendar() {
var spreadsheet = SpreadsheetApp.getActive().getSheetByName('XCALENDAR')
var calendarID = spreadsheet.getRange("O1").getValue();
var eventCal = CalendarApp.getCalendarById(calendarID);
var signups = spreadsheet.getRange("A5:P5").getValues();
for (x=0; x<signups.length;x++)
{
var shift = signups[x];
var startTime = shift[3];
var endTime = shift[5];
var nameevent= shift[1];
var desc= shift[13];
var color = shift[15];
var event = eventCal.createEvent(nameevent, startTime, endTime,{description:desc});
if(color){
event.setColor(CalendarApp.EventColor[color]);
}
}
}

To concatenate date (d) and time (t), you can do it this way
new Date(d.getFullYear(), d.getMonth(), d.getDate(), t.getHours(), t.getMinutes(), t.getSeconds())
try with
function createEvent() {
// A = title, B = description, C = location, D = begin .. E = at, F = end ... G = at
const myCalend = CalendarApp.getCalendarById("xxxxxxxxxxxx#gmail.com");
const sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
const [headers, ...data] = sh.getRange('A1:H' + sh.getLastRow()).getValues()
const colID = 8; // H
data.forEach((r, index) => {
if (r[colID - 1] == '') {
let [title, desc, loc] = [r[0], r[1], r[2]]
let [bd, bh, ed, eh] = [r[3], r[4], r[5], r[6]]
let id = (myCalend.createEvent(
title,
new Date(bd.getFullYear(), bd.getMonth(), bd.getDate(), bh.getHours(), bh.getMinutes(), bh.getSeconds()),
new Date(ed.getFullYear(), ed.getMonth(), ed.getDate(), eh.getHours(), eh.getMinutes(), eh.getSeconds()),
{
description: desc,
location: loc
}).getId())
sh.getRange(index + 2, colID).setValue(id)
}
})
}
edit
according to your spreadsheet, and assuming that dates are as dd/MM/yyyy, you can use (the eventID will be stored in column M=13 and prevent duplicating event)
function sendToCal() {
var spreadsheet = SpreadsheetApp.getActive().getSheetByName('Foglio1')
let eventCal = CalendarApp.getCalendarById("xxxxxxxxx#gmail.com");
var signups = spreadsheet.getRange("A2:M" + spreadsheet.getLastRow()).getDisplayValues();
var col = 13; // M
for (x = 0; x < signups.length; x++) {
var shift = signups[x];
if (shift[(col - 1)] == '') {
let [d, e, f, g] = [shift[3].split("/"), shift[4].split(":"), shift[5].split("/"), shift[6].split(":")]
let [nameevent, desc, color] = [shift[1], shift[11], shift[12]]
var startTime = new Date(parseInt(d[2]), parseInt(d[1])-1, parseInt(d[0]), parseInt(e[0]), parseInt(e[1]), 0)
var endTime = new Date(parseInt(f[2]), parseInt(f[1])-1, parseInt(f[0]), parseInt(g[0]), parseInt(g[1]), 0)
var event = eventCal.createEvent(nameevent, startTime, endTime, { description: desc });
spreadsheet.getRange(+x + 2, col).setValue(event.getId())
if (color) {
event.setColor(CalendarApp.EventColor[color]);
}
}
}
}

Current Date and Time
function currentdatetime() {
const second = 1000;
const minute = 60 * second;
const hour = minute * 60;
const day = hour * 24;
const dt = new Date();
const dtv = dt.valueOf();
const td = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate())
const dv = td.valueOf();
const d = dtv - dv;
let hours = Math.floor(d % day / hour);
let minutes = Math.floor(d % day % hour / minute);
let seconds = Math.floor(d % day % hour % minute / second);
Logger.log(`Date: ${td.getMonth() + 1}/${td.getDate()}/${td.getFullYear()} - Time:${hours}:${minutes}:${seconds}`)
}
Execution log
9:05:08 AM Notice Execution started
9:05:09 AM Info Date: 5/4/2022 - Time:9:5:9
9:05:09 AM Notice Execution completed
A simpler way
function currentdatetime() {
const dt = new Date();
Logger.log(`Date: ${dt.getMonth() + 1}/${dt.getDate()}/${dt.getFullYear()} - Time:${dt.getHours()}:${dt.getMinutes()}:${dt.getSeconds()}`)
}
Execution log
9:11:19 AM Notice Execution started
9:11:20 AM Info Date: 5/4/2022 - Time:9:11:20
9:11:20 AM Notice Execution completed
Super simple way
function currentdatetime() {
Logger.log(Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"MM/dd/yyyy - HH:mm:ss"))
}
Execution log
9:16:22 AM Notice Execution started
9:16:23 AM Info 05/04/2022 - 09:16:23
9:16:23 AM Notice Execution completed
Joining date and time
function currentdatetime(M=5,d=4,y=2022,H=9,m=28,s=0) {
const dt = new Date(y,M-1,d,H,m,s);
Logger.log(Utilities.formatDate(dt,Session.getScriptTimeZone(),"MM/dd/yyyy HH:mm:ss"));
return dt;
}
Execution log
9:29:38 AM Notice Execution started
9:29:39 AM Info 05/04/2022 09:28:00
9:29:39 AM Notice Execution completed

Related

set value of row for previous month

Setting value of each row that has a date of last month, I am stumped about how to get the result I want.
function hideRows() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Archived Videos");
const vs = sh.getDataRange().getValues();
const dtv = new Date(new Date().getFullYear(),new Date().getMonth() - 1,new Date().getDate()).valueOf();
let rows = [];
vs.forEach((r,i) => {
if(new Date(r[0]).valueOf() < dtv) {
rows.push(i+1);
var val = sh.getRange(i + 1,1,1,20 + 1).setValue(null);
}
})
}
I need to set each row that is from previous month to null. My code right now sets each row that is exactly one month ago or older to null. The final result should be that If today is any date in Sept all of August will set to null.
Edited: I took Coopers answer but now need it to be 2 months back and leave all of Aug and Sept. See comment below for clarification.
Setting the date in the rows of the previous month to null
function hideRows() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Archived Videos");
const vs = sh.getDataRange().getValues();
const dtv0 = new Date(new Date().getFullYear(),new Date().getMonth() - 2, Date().getDate()).valueOf();
const dtv1 = new Date(new Date().getFullYear(),new Date().getMonth(), Date().getDate()).valueOf();
let rows = [];
vs.forEach((r,i) => {
let d = new Date(r[0]);
let dv = d.valueOf();
if(dv >= dtv0 && dv < dtv1) {
rows.push(i+1);
sh.getRange(i + 1,1).setValue(null);
}
})
}

Script calls newDate and adds 5 days. I am looking to format the output to just date

Script for current date + 5 sends an email with exact 5 days from now. I want this to only output the date leaving out the timestamp
current output is: Sun Jul 10 2022 09:29:16 GMT-0400 (Eastern
Daylight Time)
expected output is: 07/0/2022
Here is what I have tried.
function findEmailAddress() {
var ss = SpreadsheetApp.getActive();
var sh1 = ss.getSheetByName('Working');
var vs1 = sh1.getRange('H1:H' + sh1.getLastRow()).getValues().flat();
var sh2 = ss.getSheetByName('Match');
var vs2 = sh2.getRange('A2:B' + sh2.getLastRow()).getValues();
var matchRows = vs2.filter(row => row[0].length && vs1.includes(row[0]));
matchRows.forEach(row => {
var mailMatch = row[1];
var curDate = new Date();
var date5 = curDate.setDate(curDate.getDate() + 5);
var dateFormat = moment(date5).format('DD/MM/YY');
var sub = "Action Required!!! 5 Days Til Expiration"
var bod = 'You have a new expiration date for completion'
+ dateFormat + ' all tasks associated with this must be complete. *This email is automatically generated do not reply*'
GmailApp.sendEmail(mailMatch, sub, bod);
});
}
I am stumped as to why this doesn't work.
Try it this way:
function findEmailAddress() {
var ss = SpreadsheetApp.getActive();
var sh1 = ss.getSheetByName('Working');
var vs1 = sh1.getRange('H1:H' + sh1.getLastRow()).getValues().flat();
var sh2 = ss.getSheetByName('Match');
var vs2 = sh2.getRange('A2:B' + sh2.getLastRow()).getValues();
var matchRows = vs2.filter(row => row[0].length && vs1.includes(row[0]));
matchRows.forEach(row => {
var mailMatch = row[1];
var curDate = new Date();
curDate.setDate(curDate.getDate() + 5);
let d = Utilities.formatDate(curDate,Session.getScriptTimeZone(),"MM/dd/yyyy")
var sub = "Action Required!!! 5 Days Til Expiration"
var bod = 'You have a new expiration date for completion'
+ d + ' all tasks associated with this must be complete. *This email is automatically generated do not reply*'
GmailApp.sendEmail(mailMatch, sub, bod);
});
}

Google Apps Script - Adding/Subtracting Time - Hours/Minutes/Seconds to a particular column in googles sheet

I want to be able to add or subtract Time - Hour/Minutes/Seconds to a particular column with some conditions using google app scripts.
Example - The Image Below.
Column A is the Original Time.
If Column D2 is "Depart To" 30 minutes will be added to the original time (column A2) which will result to the time in Column C2
while If Column D4 is "Arrive from" 30 minutes will be subtracted from the original time (column D2) which will result to the time in Column C4.
which script can I use to achieve this?
Try this:
function myFunction() {
var sh = SpreadsheetApp.getActiveSpreadsheet();
var ss = sh.getSheetByName("Sheet1");
var range = ss.getRange(2, 1, ss.getLastRow()-1, 4); //get A2:D4 range
var data = range.getDisplayValues(); //get values
data.forEach(row => { // loop each sub-array returned by getDisplayValues
var time = row[0].split(":"); //split the column a to get hour and minutes
var hour = time[0];
var minutes = time[1];
var fDate = new Date(row[1]) //create new Date object by using column b
fDate.setHours(hour) //set the hour of new Date Object
fDate.setMinutes(minutes) //set the minute of new Date Object
if(row[3].toLowerCase() == "depart to"){
fDate.setMinutes(fDate.getMinutes() + 30); // add 30 minutes to current date object
row[2] = Utilities.formatDate(fDate, Session.getScriptTimeZone(), "H:mm");
}else if(row[3].toLowerCase() == "arrive from"){
fDate.setMinutes(fDate.getMinutes() - 30); // minus 30 minutes to current date object
row[2] = Utilities.formatDate(fDate, Session.getScriptTimeZone(), "H:mm");
}
})
range.setValues(data) //write values to sheet
}
Test Data:
Output:
References:
Date Object
Spreadsheet Class
Range Class
Adding and subtracting dates
function addsubDates() {
const mA = [...Array.from(new Array(12).keys(), x => Utilities.formatDate(new Date(2021, x, 15), Session.getScriptTimeZone(), "MMM"))];//month array
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const vs = sh.getRange(2, 1, sh.getLastRow() - 1, 4).getDisplayValues();//get as string
let vo = vs.map((r, i) => {
let t = r[0].toString().split(':');
let d = r[1].toString().split('-');
let dt = new Date(parseInt(d[2]), mA.indexOf(d[1]), parseInt(d[0]), parseInt(t[0]), parseInt(t[1]));//base date
let a = 0;
if (r[3].toString().toLocaleLowerCase().includes('arrive')) { a = 30; }//adjustments
if (r[3].toString().toLocaleLowerCase().includes('depart')) { a = -30 }
return [Utilities.formatDate(new Date(dt.valueOf() + a * 60000), ss.getSpreadsheetTimeZone(), "HH:mm")];
})
sh.getRange(2, 3, vo.length, vo[0].length).setValues(vo);
}
Data:
21:46
17-Oct-2020
21:16
Depart To
21:47
17-Oct-2020
21:17
Depart To
21:48
17-Oct-2020
22:18
Arrive From
21:49
17-Oct-2020
22:19
Arrive From
21:50
17-Oct-2020
21:20
Depart To
21:51
17-Oct-2020
21:21
Depart To
21:52
17-Oct-2020
22:22
Arrive From
21:53
17-Oct-2020
22:23
Arrive From
Try this formula. Time is hours where 24 hours = 1 so 0.5/24 is a half hour.
=IF(D1="Depart To",A1+(0.5/24),A1-(0.5/24))

Code to delete outdated entries on a google sheet

I found this code on here which should work perfectly for me. Was just hoping someone could change the code to delete entries that have dates that are 2 weeks old or older. So if the script were to run today, it would delete any rows that are October 26th or older.
function DeleteOldEntries() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("MASTER");
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
Deleting Rows in a forEach loop
function DeleteOldEntries() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("MASTER");
const sr = 3;//guessing data start on row 3
const vs = sh.getRange(sr, 1, sh.getLastRow() - sr + 1, sh.getLastColumn()).getValues();
let d = 0;//delete counter
const dtv = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - 15).valueOf();
vs.forEach((r, i) => {
let cdt = new Date(r[2]);//assume date is in column 3
let cdtv = new Date(cdt.getFullYear(), cdt.getMonth(), cdt.getDate()).valueOf();
if (cdtv < dtv) {
sh.deleRow(i + sr - d++);
}
});
}
Date.valueOf()
I believe your goal is as follows.
From your script and question, you want to delete the rows when the date of column "C" is before 2 weeks from today.
In this case, how about the following modification? In your script, when the value of column "C" is the date object, you are comparing the date object.
From:
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
To:
var currentDate = new Date();
currentDate.setDate(currentDate.getDate() - 14); // Added: This means before 2 weeks from today.
var d = currentDate.getTime(); // Added
for (i = lastrow; i >= 3; i--) {
var tempDate = values[i - 1][2];
if ((tempDate != NaN) && (tempDate.getTime() <= d)) { // Modified
sheet.deleteRow(i);
}
}
}
References:
getDate()
setDate()
Compare two dates with JavaScript

google-apps-script spreadsheet get start time and end time from multiple rows

I'm trying to write a script for my spreadsheet that reads 2 columns (A & B) with A: start date + time and B: end Date + time. The dates are the same day but I get it with the export from the program.
what I'm trying to do with this is gather all the rows that are from the first day of the month, get the start time and from the last row the end time.
The Amount of rows per day is dynamic.
Per day, the start goes in a cell and the end goes in a cell.
Example of sheet
Started with this and got stuck at filtering the values per day:
function hourCalculator()
{
var SSA = SpreadsheetApp.getActiveSpreadsheet(),
sheet = SSA.getSheetByName("Example"),
data = sheet.getDataRange()
.getValues();
for (var i = 1; i < data.length; ++i) {
var day = 1,
maxDay = 32,
row = data[i],
actualSDay = new Date(row[0]),
actualSDateString = Utilities.formatDate(actualSDay, 'Amsterdam', 'dd-MM-yyyy'),
actualSDayNumber = Utilities.formatDate(actualSDay, 'Amsterdam', 'd'),
actualSTimeString = Utilities.formatDate(actualSDay, 'Amsterdam', 'HH:mm'),
actualEDay = new Date(row[1]),
actualEDateString = Utilities.formatDate(actualEDay, 'Amsterdam', 'dd-MM-yyyy'),
actualEDayNumber = Utilities.formatDate(actualEDay, 'Amsterdam', 'd'),
actualETimeString = Utilities.formatDate(actualEDay, 'Amsterdam', 'HH:mm'),
startDayNumber = Number(actualSDayNumber),
endDayNumber = Number(actualEDayNumber),
writeStart = row[6],
writeStop = row[7];
Logger.log(actualSDay);
}
}
Below code should work, Test it. If you see different time values then do check time zone of your spreadsheet and you script file.
function start(){
var Data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Example').getRange("A:B").getValues();
var startStopArray = [];
for(var i=1;i<=31;i++){
startStopArray.push([getStartTimeOfDay(i, Data), getEdTimeOfDay(i, Data)])
}
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Example').getRange("G2:H32").setValues(startStopArray);
}
function getStartTimeOfDay(day, Data){
var len = Data.length;
for(var i=1;i<len;i++){
if(Data[i][0] == "") break;
var dateIs = new Date(Data[i][0]);
if(dateIs.getDate() == day){
var hrs = dateIs.getHours()%12;
var mins = dateIs.getMinutes();
return hrs+":"+mins;
}
}
return "";
}
function getEdTimeOfDay(day, Data){
var len = Data.length;
var hhmm = "";
for(var i=1;i<len;i++){
if(Data[i][1] == "") break;
var dateIs = new Date(Data[i][1]);
if(dateIs.getDate() > day) break;
if(dateIs.getDate() == day){
var hrs = dateIs.getHours()%12;
var mins = dateIs.getMinutes();
hhmm = hrs+":"+mins;
}
}
return hhmm;
}