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.
2 thoughts on “Get The Difference Between Two Dates With subtract()”
How can you make it so you can use the number of days in calculations?
Can you share your script?
To subtract days from a GlideDateTime (GDT) variable in ServiceNow, you can use the subtract() method. This method allows you to subtract a specified duration from the current GDT object, effectively moving it back in time.
Here’s an example of how you can subtract a number of days from a GDT object:
// Create a new GlideDateTime object for the current date and time
var now = new GlideDateTime();
// Subtract 5 days from the current date and time
// Output the new date and time to the console
gs.info('New date and time: ' + now.getDisplayValue());