Usage of the .subtract() method

atishaytoma
Tera Contributor

What is the .subtract() method used for. 

 

7 REPLIES 7

AshishKM
Kilo Patron
Kilo Patron

Hi @atishaytoma,

 

Please refer below KB for the same.

 

https://support.servicenow.com/kb?id=kb_article_view&sysparm_article=KB0824807

 

-Thanks,

AshishKM


Please mark this response as correct and helpful if it helps you can mark more that one reply as accepted solution

Ankur Bawiskar
Tera Patron
Tera Patron

@atishaytoma 

subtract method in ServiceNow is used to calculate difference between 2 GlideDate or 2 GlideDateTime objects

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Juhi Poddar
Kilo Patron

Hello @atishaytoma 

Below are examples to demonstrate how the subtract() method works in ServiceNow for different use cases:

  • Subtract two GlideDateTime objects

This example calculates the duration between two GlideDateTime objects and outputs it in a human-readable format.

 

var pastDate = new GlideDateTime("2020-04-16 20:00:00");
var currDate = new GlideDateTime("2020-04-17 20:30:55");
gs.print("pastDate: " + pastDate); 
gs.print("currDate: " + currDate);
var dur = GlideDateTime.subtract(pastDate,currDate);
gs.print(dur.getDisplayValue()); 

 

  • Subtract GlideDateTime and GlideDuration object

This subtracts a predefined duration (1 day) from a GlideDateTime object and displays the resulting date and time.

 

var gdt = new GlideDateTime(); // Current DateTime
gs.print("Current Date and Time: " + gdt);
var duration = new GlideDuration();
duration.setValue("1 00:00:00"); // Set duration to 1 day
gdt.subtract(duration);
gs.print("Date and Time after subtraction: " + gdt);

 

  • Subtract GlideDate to any time in milliseconds

This demonstrates subtracting a specific duration (in milliseconds) from a GlideDate object.

 

// Create a GlideDate object for the current date
var glideDate = new GlideDate();

// Log the current date
gs.info("Current Date: " + glideDate.getValue());

// Subtract 5 days from the current date
glideDate.subtract(5 * 24 * 60 * 60 * 1000); // Subtract milliseconds for 5 days

// Log the updated date
gs.info("Updated Date (5 days subtracted): " + glideDate.getValue());

 

These examples cover common scenarios of using the subtract() method with GlideDateTime, GlideDate, and GlideDuration. You can try each example in Scripts - Background to learn more about how the subtract() method works in different contexts. This will help you better understand the behavior and possible use cases of date and time manipulation in ServiceNow.

Hope this helps!

 

"If you found my answer helpful, please like and mark it as an "accepted solution". It helps future readers to locate the solution easily and supports the community!"

 

Thank You
Juhi Poddar

Bert_c1
Kilo Patron