Use subtract() To Get A Date Difference

Here is a quick server side script where you can get the duration difference, between 2 GlideDateTime objects.

Remember that this is only available to run on the server.

So only in a business rule or script include, this cannot be used anywhere on the client side, unless you use a GlideAjax script.

There are other ways to do this, but I think people overcomplicate things.

This is by far the simplest and most performant method of getting a date difference.

Get A Duration Or Date Difference With subtract()

Here is an example of the script you would write to get a difference between 2 date objects in ServiceNow.

var gdt1 = new GlideDateTime("2021-08-28 09:00:00");
var gdt2 = new GlideDateTime("2021-08-31 08:00:00");
 
var dur = GlideDateTime.subtract(gdt1, gdt2); //the difference between gdt1 and gdt2
gs.info(dur.getDisplayValue());

This will return the following:

2 Days 23 Hours

Technically, using subtract with GlideDateTime objects returns a GlideDuration object, which in this instance is: 2 Days 23 Hours.

If you have any questions below, we’d love to hear them.