Format current time in Google App Scripts - google-apps-script

How can you set the current time with google app scripts? I'm having a tough time finding the Time documentation.
I'm able to get the time in milliseconds using.
(new Date()).getTime()
I'd like to now format this time as 11:56 AM. I'm using the Date documentation. I've tried using toLocaleTimeString() from javascript but it is not defined in app scripts

For formatting a date, what you want is the Utilities.formatDate() function, documented here: https://developers.google.com/apps-script/reference/utilities/utilities#formatDate(Date,String,String)
Usage to get the time only would be:
Utilities.formatDate(YOUR DATE,YOUR TIMEZONE, 'HH:mm')
replacing YOUR DATE and YOUR TIMEZONE with the appropriate values.

Related

How to pass timezone in getEvents(startTime, endTime) method in google appscript?

I am fetching events from google calendar using getEvents(startTime, endTime) method. https://developers.google.com/apps-script/reference/calendar/calendar#getEvents(Date,Date) According to this documentation on Google, we can pass the timezone in which we are sending start & end date but how? That is not mentioned . So how can we pass timezone while fetching events from Google Calendar using method getEvents(startTime, endTime) in apps-script
The Date type handles timezones; see more informations here : https://developers.google.com/google-ads/scripts/docs/features/dates
You can use for example getTimezoneOffset() to retrieve the timezone of a given Date.

Dealing with time zones in Apps Script when importing data into Google Sheets

I'm having some trouble getting time zones to play nicely with a custom Sheets extension when importing data into Google Sheets.
It seems that there is sometimes a mismatch between time zones that results in incorrect behavior.
Here's my code to try to combine some date data columns in order to display a properly formatted date:
activeSheetTimeZone = Session.getScriptTimeZone();
//Merge dates into start and end only
var range1 = sheet.getRange(2,shiftDayIndex,sheet.getLastRow()-1,1).getValues().map(date => Utilities.formatDate(date[0], activeSheetTimeZone,"MMM d"));
var range2 = sheet.getRange(2,shiftStartIndex,sheet.getLastRow()-1,1).getValues().map(date => Utilities.formatDate(date[0], activeSheetTimeZone,"h:mm a"));
var range3 = sheet.getRange(2,shiftEndIndex,sheet.getLastRow()-1,1).getValues().map(date => Utilities.formatDate(date[0], activeSheetTimeZone,"h:mm a"));
When importing a .csv file, this causes the dates to be shifted inappropriately (looks like it's treating the imported data as GMT +0 and adjusting it to Central Time according to the project settings).
However! If the user does certain things in the imported sheet, it seems to synchronize the imported data to be in Central Time, so the formatted dates show up correctly. It's not totally clear to me which actions cause the sync and which ones don't. It's also not clear to me if I can somehow force the "time zone sync" to occur in the scripting for the custom extension.
Does anyone have a way to make sure that there aren't time zone conflicts when using custom Google Sheets extensions?
Edit: Here's How to Fix This
As Ale13 says below "You can also change the time zone programmatically by using the setSpreadsheetTimeZone(timezone) method."
This is the solution here.
This issue is not caused by a script/sheet time zone mismatch, since both getScriptTimeZone and getSpreadsheetTimeZone result in the same behavior.
Instead, it seems that imported data can exist in a "phantom UTC" state until some sort of action is taken on the imported data to cause it to sync with the Spreadsheet's time zone.
Adding a line to the extension with setSpreadsheetTimeZone solves the issue.
The script's time zone is different from the spreadsheet's time zone. Hence, the two methods will return two different values if the time zones are not the same.
getSpreadsheetTimeZone() - will return the time zone of the spreadsheet, specified in "long" format
So depending on this, when you import the .csv file in your spreadsheet, they will be converted to the spreadsheet's time zone.
getScriptTimeZone() - will return the script's time zone.
This fact is also mentioned in Google's official documentation.
Note that spreadsheets have a separate time zone, which can be changed by clicking File > Spreadsheet settings in Google Sheets. Spreadsheet time zones that differ from the script time zone are a frequent source of scripting bugs.
You can also change the time zone programmatically by using the setSpreadsheetTimeZone(timezone) method.
Reference
Apps Script Spreadsheet Class - getSpreadsheetTimeZone();
Apps Script Session Class - getScriptTimeZone().

Is it possible to get a "live" version of the last modified date of a google drive file?

I've noticed that when i open a file in google drive and modify an element and ask for the last modified date it gives me the actual time and date of the modification, while if i keep the file open and then make changes for the second time and ask for the modified date, the date and time remains stuck to the first modification date for about two minutes.
I was wondering if there's a way to get the actual "live" modified date of a google drive file using python's API or if anyone knows another method/program language where it's possible to get this information "live".
Thanks for your help!
No there isn't. The granularity of Drive updates isn't something you can influence and there is only a single API property that you can fetch.

Profiling the Performance of a Google App Script

I've written a Google App Script to pull in Google Analytics data into a Google Spreadsheet. It's a fairly long running script making multiple requests to the GA Reporting API, it also uses Google App's ScriptDB.
Is there a good way of profiling each step of the scripts performance so I can figure out what areas are taking the longest, so I can begin optimizing in certain areas?
As a complement to Fred's answer, define a variable start at the top of your script
var start = new Date().getTime();
then in a few Logger.log() placed a strategic points use
Logger.log(new Date().getTime()-start);
and you'll get a pretty good idea of what is going on...
The Execution Transcript is very useful for this kind of thing.
You can also put Logger.log() statements all over the place that measure the time since the last log. That way you can find areas that take longer to execute.
I have a spreadsheet where I copy the log after an execution and then formulas + conditional formatting help me identify areas that are slow.
The basic tools are the execution transcript and Class Logger (mentioned on previous answers)
Nowadays we could use Stackdriver logging and Class Console which includes console.time and console.timeEnd.
And to make things betters, also we could send Stackdriver logging to Google Data Studio through BigQuery, so we could build helpful metrics to track profiling data.
References
Stackdriver Logging for Google Apps Script is now available
Identify and understand errors in Apps Script with Stackdriver
To correct Serge's answer, where call to Date function has a problem, you can use this solution.
function myFunction() {
var start_time = new Date().getTime();
/*
your code goes here
*/
Logger.log('Total execution time is :' + (new Date().getTime()-start_time) + ' ms');
}
you can replace the comment lines with your code. After execution press Ctrl + Enter or Command ⌘ + Enter on Mac to see the logs. You will get something like following:
[17-01-18 12:25:58:932 UTC] Total execution time is :16586 ms
So here total execution time is 16586 ms or in other words 16.586 Seconds.
In addition to above you can add the following snippet in between your code to measure execution time from different parts.
Logger.log('Execution time till checkpoint 1:' + (new Date().getTime()-start_time) + ' ms');
You should probably use the methods console.time(label) and console.timeEnd(label) since you could get negative results when using Date.

Getting Date a Year From Now in Google Apps Script

I'm working on a spreadsheet in Google Drive to keep track of when we need to get our employees their annual reviews. As part of the calculations, I need to be able to compute their anniversary dates by adding years to their start dates. I'm trying this:
returnDate = returnDate.setYear( returnDate.getYear() + 1);
Alas, the scripting language that google supports seems to lack many of the useful functions of a fully-fledged Javascript Date object, as I get this error on that line when I try to run it:
TypeError: Cannot find function setYear in object 1357106400000. (line 28, file "Code")
So, how can one compute a series of anniversary dates using the tools available in Google Apps Script?
Thanks for any help.
Works like this :
function addOneYear(y){
var fullYear = y.getFullYear();
return new Date(y.setFullYear(fullYear+1));
}
According to Javascript specifications here getYear and setYear are not recommended