Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Moment.js in ServiceNow?

Our team is trying to use Moment.js in our instance, but can't seem to get it to work. Here are a couple questions we have about it:

  1. We noticed that there is a dependency out of the box called moment-timezone-with-data-2010-2020-v0.5, is this the same as moment.js? If so, does this mean we don't need to bring in moment.js as a new dependency?
  2. We tried using the above ootb dependency AND tried to bring in moment.js to use in a widget, and we keep getting a console error saying that moment is undefined. Can someone provide some instructions on how to correctly get either one of these dependencies to work?
  3. If we wanted to use moment.js on a platform business rule, what do we have to do to make that happen? Are you able to access a dependency via business rule?

Thanks!

like image 880
Dave Avatar asked Nov 26 '25 03:11

Dave


1 Answers

Here's how I was able to do it:

Create a Script Include with the following attributes:

  • script name is "moment" (it needs to have this exact name)
  • scope is either global or the same scope as your project (I used global)
  • set as client callable

Paste the code from MomentJS 2.22.1 into the script body.

To verify that you can access your Script Include, open a Background Script and run the following test code:

var calendar = moment().add(1, 'days').calendar();
gs.log("calendar test: " + calendar);

var dayCount = moment().diff('1809-02-12', 'days');
gs.log('Abraham Lincoln was born ' + dayCount + " days ago!");

To answer your question on moment-timezone-with-data-2010-2020-v0.5: no's it's not the same; here's a link to Moment Timezone which is a different library by the same organization.

As of the time of this post, 2.22.1 is the newest version that runs in ServiceNow. There are newer versions of MomentJS, but they're too new for the SN interpreter.

You can also create a UI Script with version 2.22.1.

like image 120
Ryan Loggerythm Avatar answered Nov 28 '25 18:11

Ryan Loggerythm