Get The Difference Between Two Dates With subtract()

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 …

date difference with subtract()

Buy The "ServiceNow Developer's Manual" Now

We've packed over a decade of ServiceNow Development advice, into a single e-book.

Buy It Now

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.



What Do You Think About This Article?

0 0 votes
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Brian Shanken
Brian Shanken
1 year ago

How can you make it so you can use the number of days in calculations?

2
0
Would love your thoughts, please comment.x
()
x