Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use momentsjs in Google Apps Script?

Tags:

I'm trying to utilize the momentjs library in Google Apps Script but I'm not clear on how to do so. I'm not sure how to add the library, so obviously running something like the following results in "Reference Error: 'moment' is not defined":

var a = moment([2007, 0, 29]); var b = moment([2007, 0, 28]); var difference = a.diff(b); 
like image 371
Jared_C Avatar asked Mar 14 '14 16:03

Jared_C


People also ask

How do you use moments in Google script?

@RafaelSlobodian the MomentAPI will be just a script with this name "MomentAPI", which will include the files, and will import this script in other script and call it like examples. Also you can use it directly in the same script like you made when calling moment() directly, it is the same also.

Can I use JavaScript in Google App script?

Google Apps Script is a rapid application development platform that makes it fast and easy to create business applications that integrate with Google Workspace. You write code in modern JavaScript and have access to built-in libraries for favorite Google Workspace applications like Gmail, Calendar, Drive, and more.

How do I get todays date in Google script?

The TODAY function in Google Sheets returns the current date. You can use it to automatically update the date in a spreadsheet cell, or to calculate the age of a person based on their date of birth. To use the TODAY function, type =TODAY() in a cell and press Enter.


1 Answers

Most people try to use the library with the key ending in 48. That library is pretty dated (it is version 2.9 which is pretty old).

Using eval and UrlFetchApp.fetch moment.js or any other external library can be used easily in google app scripts.

function testMoment() {   eval(UrlFetchApp.fetch('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js').getContentText());   var date = moment().format("MMM Do YY");   Logger.log(date) } 

You may either host the moment.js on your own server, or use a CDN like cloudflare CDN to reference the library.

For cloudflare, here is the page which shows moment.js versions and their urls:

https://cdnjs.com/libraries/moment.js/


As of writing this post 2.18.1 is the latest version.

For the example posted by OP it will look like this:

function testMomentDifference() {   eval(UrlFetchApp.fetch('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js').getContentText());   var a = moment([2007, 0, 29]);   var b = moment([2007, 0, 28]);   var difference = a.diff(b);   Logger.log(difference); } 
like image 171
apadana Avatar answered Nov 16 '22 19:11

apadana