change Time inside object - google-apps-script

My code creates an event inside Google Calendar, I need to get the value of start time and add 2 hours to get my end time.
Here's an example of the array my function returns:
[[kljlkjl, Manaf, Tue Jun 25 16:00:00 GMT+03:00 2019]]
This is part of the code that I want to fix:
var data = ss.getRange("A"+activeRow+":G"+activeRow).getValues();
if(cellContent === "Manaf") {
Logger.log(data);
Manaf.createEvent(data[0][0],data[0][2],data[0][2],{description: "First call "+ data[0][0]}) ;

Solution
To increment hours by 2, you can utilize getHours() and setHours() methods of the Date built-in object with the instance written into data variable. As you need to increment hours dynamically, you’ll have to pair these methods like this: dateInstance.setHours(dateInstance.getHours()+2).
Sample
So, your script with this modification will look like this (please, note that I also updated your code to work directly with 1-d Array as your range is always one-row):
var data = ss.getRange("A"+activeRow+":G"+activeRow).getValues()[0];
var start = data[2];
var end = new Date(start); //create new Date to persist start;
end.setHours(start.getHours()+2); //add 2 hours;
if(cellContent === "Manaf") {
Manaf.createEvent(data[0],start,end,{description: "First call "+ data[0]});
}
Useful links
Date built-in object reference;
getHours() method deeplink;
setHours() method deeplink;

Related

Google Script Forcing Date Format [duplicate]

I'm trying to get from a time formatted Cell (hh:mm:ss) the hour value, the values can be bigger 24:00:00 for example 20000:00:00 should give 20000:
Table:
if your read the Value of E1:
var total = sheet.getRange("E1").getValue();
Logger.log(total);
The result is:
Sat Apr 12 07:09:21 GMT+00:09 1902
Now I've tried to convert it to a Date object and get the Unix time stamp of it:
var date = new Date(total);
var milsec = date.getTime();
Logger.log(Utilities.formatString("%11.6f",milsec));
var hours = milsec / 1000 / 60 / 60;
Logger.log(hours)
1374127872020.000000
381702.1866722222
The question is how to get the correct value of 20000 ?
Expanding on what Serge did, I wrote some functions that should be a bit easier to read and take into account timezone differences between the spreadsheet and the script.
function getValueAsSeconds(range) {
var value = range.getValue();
// Get the date value in the spreadsheet's timezone.
var spreadsheetTimezone = range.getSheet().getParent().getSpreadsheetTimeZone();
var dateString = Utilities.formatDate(value, spreadsheetTimezone,
'EEE, d MMM yyyy HH:mm:ss');
var date = new Date(dateString);
// Initialize the date of the epoch.
var epoch = new Date('Dec 30, 1899 00:00:00');
// Calculate the number of milliseconds between the epoch and the value.
var diff = date.getTime() - epoch.getTime();
// Convert the milliseconds to seconds and return.
return Math.round(diff / 1000);
}
function getValueAsMinutes(range) {
return getValueAsSeconds(range) / 60;
}
function getValueAsHours(range) {
return getValueAsMinutes(range) / 60;
}
You can use these functions like so:
var range = SpreadsheetApp.getActiveSheet().getRange('A1');
Logger.log(getValueAsHours(range));
Needless to say, this is a lot of work to get the number of hours from a range. Please star Issue 402 which is a feature request to have the ability to get the literal string value from a cell.
There are two new functions getDisplayValue() and getDisplayValues() that returns the datetime or anything exactly the way it looks to you on a Spreadsheet. Check out the documentation here
The value you see (Sat Apr 12 07:09:21 GMT+00:09 1902) is the equivalent date in Javascript standard time that is 20000 hours later than ref date.
you should simply remove the spreadsheet reference value from your result to get what you want.
This code does the trick :
function getHours(){
var sh = SpreadsheetApp.getActiveSpreadsheet();
var cellValue = sh.getRange('E1').getValue();
var eqDate = new Date(cellValue);// this is the date object corresponding to your cell value in JS standard
Logger.log('Cell Date in JS format '+eqDate)
Logger.log('ref date in JS '+new Date(0,0,0,0,0,0));
var testOnZero = eqDate.getTime();Logger.log('Use this with a cell value = 0 to check the value to use in the next line of code '+testOnZero);
var hours = (eqDate.getTime()+ 2.2091616E12 )/3600000 ; // getTime retrieves the value in milliseconds, 2.2091616E12 is the difference between javascript ref and spreadsheet ref.
Logger.log('Value in hours with offset correction : '+hours); // show result in hours (obtained by dividing by 3600000)
}
note : this code gets only hours , if your going to have minutes and/or seconds then it should be developped to handle that too... let us know if you need it.
EDIT : a word of explanation...
Spreadsheets use a reference date of 12/30/1899 while Javascript is using 01/01/1970, that means there is a difference of 25568 days between both references. All this assuming we use the same time zone in both systems. When we convert a date value in a spreadsheet to a javascript date object the GAS engine automatically adds the difference to keep consistency between dates.
In this case we don't want to know the real date of something but rather an absolute hours value, ie a "duration", so we need to remove the 25568 day offset. This is done using the getTime() method that returns milliseconds counted from the JS reference date, the only thing we have to know is the value in milliseconds of the spreadsheet reference date and substract this value from the actual date object. Then a bit of maths to get hours instead of milliseconds and we're done.
I know this seems a bit complicated and I'm not sure my attempt to explain will really clarify the question but it's always worth trying isn't it ?
Anyway the result is what we needed as long as (as stated in the comments) one adjust the offset value according to the time zone settings of the spreadsheet. It would of course be possible to let the script handle that automatically but it would have make the script more complex, not sure it's really necessary.
For simple spreadsheets you may be able to change your spreadsheet timezone to GMT without daylight saving and use this short conversion function:
function durationToSeconds(value) {
var timezoneName = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
if (timezoneName != "Etc/GMT") {
throw new Error("Timezone must be GMT to handle time durations, found " + timezoneName);
}
return (Number(value) + 2209161600000) / 1000;
}
Eric Koleda's answer is in many ways more general. I wrote this while trying to understand how it handles the corner cases with the spreadsheet timezone, browser timezone and the timezone changes in 1900 in Alaska and Stockholm.
Make a cell somewhere with a duration value of "00:00:00". This cell will be used as a reference. Could be a hidden cell, or a cell in a different sheet with config values. E.g. as below:
then write a function with two parameters - 1) value you want to process, and 2) reference value of "00:00:00". E.g.:
function gethours(val, ref) {
let dv = new Date(val)
let dr = new Date(ref)
return (dv.getTime() - dr.getTime())/(1000*60*60)
}
Since whatever Sheets are doing with the Duration type is exactly the same for both, we can now convert them to Dates and subtract, which gives correct value. In the code example above I used .getTime() which gives number of milliseconds since Jan 1, 1970, ... .
If we tried to compute what is exactly happening to the value, and make corrections, code gets too complicated.
One caveat: if the number of hours is very large say 200,000:00:00 there is substantial fractional value showing up since days/years are not exactly 24hrs/365days (? speculating here). Specifically, 200000:00:00 gives 200,000.16 as a result.

Google Apps Script: Calendar Service: Find first event in CalendarEventSeries

I'd like to calculate the age of a person whose birthday exists as event series within my calendar. To do this I need to know the first event within this series and that's the question: how to get the first event of a series from an actual event?
Thanks
Ronny
The other answer doesn't actually answer the initial request, the CalendarApp has no method to get the start date of a recurring event.
You should use the advanced Calendar API (must be enabled manually, see below and follow instructions)
Then use the advanced API to get the information you want, (the auto complete feature works on these methods too so you can easily see what is available)
Test code below, note that event ID is different for the advanced Calendar API, you have to remove the part after '#'.
function createTestEvents() {
var recurrence = CalendarApp.newRecurrence().addWeeklyRule().times(10);
var testEvent = CalendarApp.getDefaultCalendar().createEventSeries('test event serie', new Date('2016/05/10'), new Date(new Date('2016/05/10').getTime()+12*3600000), recurrence);
var id = testEvent.getId();
Logger.log('Event Series ID: ' + id);
viewTestEvent(id)
}
function viewTestEvent(id){
var event= CalendarApp.getDefaultCalendar().getEventSeriesById(id);
var calId = CalendarApp.getDefaultCalendar().getId();
Logger.log('event title = '+event.getTitle());
var AdvanncedId = id.substring(0,id.indexOf('#'));
Logger.log('AdvanncedId = '+AdvanncedId);
var testEvent = Calendar.Events.get(calId, AdvanncedId);
Logger.log('testEvent start = '+ testEvent.start);
return testEvent;
}
function test(){ // a few examples of what you can retrieve...
var event = viewTestEvent('59buf7nq6nr6qo79bh14kmsr6g#google.com');
Logger.log('\n\nstart = '+event.start);
Logger.log('\n\ncreated on = '+event.created);
Logger.log('\n\nend on = '+event.end);
Logger.log('\n\nrecurrence = '+event.recurrence);
}
You need to use the startDate parameter to get the date of the first event in the series (only the day is used; the time is ignored).
var eventSeries = CalendarApp.getDefaultCalendar().createAllDayEventSeries('No Meetings',
new Date('January 2, 2013 03:00:00 PM EST'),
CalendarApp.newRecurrence().addWeeklyRule()
.onlyOnWeekday(CalendarApp.Weekday.WEDNESDAY)
.until(new Date('January 1, 2014')));
Logger.log('Event Series ID: ' + eventSeries.getId());
You can also get the event series with the given ID using getEventSeriesById(iCalId).
If the ID given is for a single CalendarEvent, then a CalendarEventSeries will be returned with a single event in the series. Note that if the event series belongs to a calendar other than the default calendar, this method must be called from that Calendar; calling CalendarApp.getEventSeriesById(id) directly will only return an event series that exists in the default calendar.
Hope this helps!

Google Apps Script and RFC 3339 issue

In the Google reference documentation I found a short function to convert RFC3339 date string to a valid Date object. The code is very simple and goes like this :
function parseDate(string) {
var parts = string.split('T');
parts[0] = parts[0].replace(/-/g, '/');
return new Date(parts.join(' '));
}
The problem is that it does not work.(I'm surprised they publish a code that doesn't work... am I missing something ?)
I also had an issue while using JSON to stringify and parse dates because the JSON method returns a UTC value (a Z at the end) and because of that I lose the Time zone information. Google's code does not handle that issue either (even if it worked).
Below is a demo code I used to test it and a solution I wrote to get what I want. Not sure it's very efficient nor well written but at least I get the result I want (I'm executing this code in a script set to GMT+2, Belgium summer time).
I'm open to any suggestion to improve this code.(and that would be the subject of this question)
I added a lot of logs and comments in the code to make it as clear as possible :
function testJSONDate() {
Logger.log('starting value : "2016/3/31 12:00:00"');
var jsDate = JSON.stringify(new Date("2016/3/31 12:00:00"));// time is 12:00 I'm in GMT+2
Logger.log('JSON.stringify value : '+jsDate);
Logger.log('JSON parse jsDate : '+JSON.parse(jsDate)); // time is 10:00, UTC
var jsDateWithoutQuotes = jsDate.replace(/"/,'');
var date = parseDate(jsDateWithoutQuotes);
Logger.log('parsed RFC3339 date using Google\'s code : '+date); // does not return a valid date
var otherFunction = parseDate2(jsDateWithoutQuotes);
Logger.log('parsed RFC3339 date using other code : '+otherFunction); // does return a valid date in my TZ
}
function parseDate(string) {
var parts = string.split('T');
parts[0] = parts[0].replace(/-/g, '/');
return new Date(parts.join(' '));
}
function parseDate2(string) {
var refStr = new Date().toString();
var fus = Number(refStr.substr(refStr.indexOf('GMT')+4,2));
Logger.log('TZ offset = '+fus);
var parts = string.split('T');
parts[0] = parts[0].replace(/-/g, '/');
var t = parts[1].split(':');
return new Date(new Date(parts[0]).setHours(+t[0]+fus,+t[1],0));
}
Logger results :
EDIT following first answer
After a small change in the code I managed to get Google's snippet to work but the problem of time zone being lost still remains because of the way JSON converts JS date objects.
new code and logger result below:
function testJSONDate() {
Logger.log('starting value : 2016/3/31 12:00:00');
var jsDate = JSON.stringify(new Date("2016/3/31 12:00:00"));// time is 12:00 I'm in GMT+2
Logger.log('JSON.stringify value : '+jsDate);
Logger.log('JSON parse jsDate : '+JSON.parse(jsDate)); // time is 10:00, UTC
var jsDateWithoutQuotesAndMillisecAndZ = jsDate.replace(/"/g,'').split('.')[0];
Logger.log('jsDateWithoutQuotesAndMillisecAndZ = '+jsDateWithoutQuotesAndMillisecAndZ);
var date = parseDate(jsDateWithoutQuotesAndMillisecAndZ);
Logger.log('parsed RFC3339 date using Google\'s code : '+date); // does not return a valid date
var otherFunction = parseDate2(jsDateWithoutQuotesAndMillisecAndZ);
Logger.log('parsed RFC3339 date using other code : '+otherFunction); // does return a valid date in the right tz
}
You have taken a little helper function out of context. It was only meant as a stopgap device to get the strings returned by a particular API (Google Calendar API) to parse correctly in Apps Script. It is not any kind of universal date converter. A project member threw it together when filing an issue, and a follow-up message in that thread points out another detail that the function doesn't handle.
As of now, the date parser in Apps Script correctly parses the following formats:
function testdate() {
Logger.log(new Date("2016/03/31 10:00:00")); // local time
Logger.log(new Date("2016/03/31 10:00:00 +2:00")); // with given offset
Logger.log(new Date("2016-03-31T08:00:00.000Z")); // in UTC
}
Note that milliseconds are required for UTC timestamp, but are not allowed for the others.
What you do with a datetime string that needs to be parsed but is not one of the above, depends on its format. If you have 2016-03-31T10:00:00 (apparently, this is what Google Calendar API returns) and this is meant to be in local time, then you need exactly what the quoted parse function does: replace T by space and - by /. If the same string represents UTC time, one needs to add .000Z at the end. And so on.

How to modify a specific instance of an event series

Let's suppose I create a recurring event that starts on Monday at 9 AM and ends at 11 AM, this event repeats every day for 3 days.
Now I want (after I have created the events using recurrence) to change the start time of the event on Tuesday while leaving the other events unchanged, how could I do ?
I can easily get the recurrence rule for this eventSeries using the advanced calendar API, it returns something like
RRULE:FREQ=DAILY;COUNT=3
This rule can be modified at will to change all the events (and I can also update the events using patch but not just for a single event.
I tried the API tryout to get every instance of this eventSeries and I can indeed see every start and end times (*see below) but I didn't find any method to get that using the Calendar API in Google Apps Script.
I didn't find a way to modify a particular instance, i.e. to write back the modified values.
Since I can do this manually in the calendar web UI I guess I should be able to do it using a script but I really don't know how.
The code I use to get the event parameters is fairly simple :
...
for(var n = 1 ; n < data.length ; n++){
if(data[n][9] == ''){continue};
var advancedID = data[n][9].substring(0,data[n][9].indexOf('#'));
Logger.log(advancedID+'\n');
ChangeEventRecurrence(calID,advancedID);
}
}
function ChangeEventRecurrence(calID,advancedID){
var event = Calendar.Events.get(calID, advancedID);
Logger.log(event.recurrence+'\n'+JSON.stringify(event));
// here I should be able to get all the instances of this eventSeries and change them if needed
}
Here is a capture of an instance I get using the API tryout :
With CalendarApp, just specify the date range to look for the single event and loop through the result to then use .setTime() :
var cal = CalendarApp.getCalendarsByName('<YOUR_CAL>')[0];
var events = cal.getEvents(new Date("April 5, 2016 08:00:00 AM"), new Date("April 5, 2016 11:30:00 AM"));
events.forEach( function(e) {
//var e = events[0];
//if ( e.getTitle() === 'Your Title' )
e.setTime(new Date("April 5, 2016 11:00:00 AM"), new Date("April 5, 2016 01:00:00 PM"));
});
I can't tell if your "specific instance" means just a single event or every Tuesday event though, or whether you have a reason to even use the Advanced Calendar API for this case.

Calculating runtime minus Timestamp

I have a form which activates a procedure via an "On form submit" trigger. At the end of this routine I want to insert the difference in time between the form's Timestamp and the current time at the end of the routine (the difference of which is only a matter of a few seconds).
I've tried many things so far, but the result I typically receive is NaN.
I thought that my best bet would be to construct the runtime elements (H,M,S) and similarly deconstruct the time elements from the entire Timestamp, and then perform a bit of math on that:
var rt_ts = Math.abs(run_time - ts_time);
(btw, I got that formula from somewhere on this site, but I'm obviously grasping at anything at this point. I just can't seem to find a thread where my particular issue is addressed)
I've always found that dealing with dates and time in Javascript is tricky business (ex: the quirk that "month" start at zero while "date" starts at 1. That's unnecessarily mind-bending).
Would anyone care to lead me out of my current "grasping" mindset and guide me towards something resembling a logical approach?
You can simply add this at the top of your onFormSubmit routine :
UserProperties.setProperty('start',new Date().getTime().toString())
and this at the end that will show you the duration in millisecs.
var duration = new Date().getTime()-Number(UserProperties.getProperty('start'))
EDIT following your comment :
the time stamp coming from an onFormSubmit event is the first element of the array returned by e.values see docs here
so I don't really understand what problem you have ??
something like this below should work
var duration = new Date().getTime() - new Date(e.values[0]).getTime();//in millisecs
the value being a string I pass it it 'new Date' to make it a date object again. You can easily check that using the logger like this :
Logger.log(new Date(e.values[0]));//
It will return a complete date value in the form Fri Mar 12 15:00:00 GMT+01:00 2013
But the values will most probably be the same as in my first suggestion since the TimeStamp is the moment when the function is triggered...
I have a function which can show the times in a ss with timestamps in column A. It will also add the time of the script itself to the first timestamp (in row 3) and show this in the Log.
Notice that the google spreadsheet timestamp has a resolution in seconds and the script timestamp in milliseconds. So if you only add, say, 300 milliseconds to a spreadsheet timestamp, it might not show any difference at all if posted back to a spreadsheet. The script below only takes about 40 milliseconds to run, so I have added a Utilities.sleep(0) where you can change the value 0 to above 1000 to show a difference.
function testTime(){
var start = new Date().getTime();
var values = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
for(var i = 2; i < values.length ; i++){
Logger.log(Utilities.formatDate(new Date(values[i][0]),Session.getTimeZone(),'d MMM yy hh:mm:ss' )); // this shows the date, in my case same as the ss timestamp.
Logger.log( new Date(values[i][0]).getTime() ); // this is the date in Milliseconds after 1 Jan 1970
}
Utilities.sleep(0); //you can vary this to see the effects
var endTime = new Date();
var msCumulative = (endTime.getTime() - start);
Logger.log(msCumulative);
var msTot = (msCumulative + new Date(values[2][0]).getTime());
Logger.log('script length in milliseconds ' + msTot );
var finalTime = Utilities.formatDate(new Date(msTot), Session.getTimeZone(), 'dd/MM/yyyy hh:mm:ss');
Logger.log ( finalTime); //Note that unless you change above to Utilities.sleep(1000) or greater number , this logged date/time is going to be identical to the first timestamp since the script runs so quickly, less than 1 second.
}