How do I use momentsjs in Google Apps Script?

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);
}

Leave a Comment