How do I use momentsjs in Google Apps Script?

前端 未结 5 2295
时光说笑
时光说笑 2020-12-15 18:09

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 l

5条回答
  •  醉梦人生
    2020-12-15 19:06

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

提交回复
热议问题