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);
@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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With