GlideSystem, GlideDateTime & GlideAggregate in ServiceNow
In the last topic, we learned how GlideRecord reads and changes records. But server scripts need more than records. They need to know who the user is, log what the script is doing, work with dates, and calculate totals.
In this, we will understand GlideSystem, GlideDateTime, and GlideAggregate in ServiceNow and how to use them in your server scripts.
What is GlideSystem (gs)?
GlideSystem in ServiceNow is a server-side class that gives you information about the system and the current logged-in user.
Here are the key things to know about GlideSystem:
Auto availability: No need to create or initialize the gs object; use it directly inside the scripts.
Get User Data: Easily fetches the details about the current user, sessions, and roles.
System Details: It allows your scripts to access core system properties and environment information.
To put these capabilities into action, developers frequently rely on specific built-in functions to manage configurations and monitor script behavior. Let’s look at two of the most important ones:
gs.log() and gs.getProperty(): Common Use Cases
gs.log() and gs.getProperty() in ServiceNow are essential parts of the server-side GlideSystem (gs) API used for tracking execution and externalizing configurations.
gs.log() is used to write messages to the ServiceNow system log. It helps developers understand what is happening inside a script and identify errors during execution.
Common Use Cases:
- Debugging and Troubleshooting: Check whether a script is running correctly, identify errors, and track unexpected behavior.
- Tracking Script Activity: Record messages to understand which steps a script has executed and which records it has processed.
- Filtering Logs: Add a custom source name to log messages so they can be easily identified and filtered in system logs.
- Checking Data: Log incoming data or variable values to verify that a script is receiving the expected information.
gs.getProperty() is used to retrieve configuration values stored in the ServiceNow System Properties (sys_properties) table.
It helps developers keep important settings separate from the script, making them easier to update without modifying the code.
Common Use Cases:
- Managing Configuration Settings: Store values such as API URLs, email addresses, and instance-specific settings in system properties instead of hardcoding them.
- Feature Toggles: Enable or disable a feature by changing a property value without editing the script.
- Managing Limits: Store values such as retry counts, time limits, or the number of records to process.
- Building Record Links: Retrieve the instance URL from a property and use it to create links to ServiceNow records.
- Controlling Debug Logs: Use a property to enable or disable debugging messages whenever required.
Important: gs.getProperty() always returns a string even if the value stored is a number or a Boolean (true/false). If you want to do numerical or boolean operations, cast the value.
What is GlideDateTime?
GlideDateTime in ServiceNow is a server-side API for working with dates and times. It provides methods for date-time operations, such as creating an object, doing date-time calculations, formatting a date-time, and converting between formats.
The most important thing to remember is how time is stored:
- A GlideDateTime object stores its value in UTC, in the format yyyy-MM-dd HH:mm:ss.
- A user sees the value in their own time zone and format.
That is why many GlideDateTime methods come in two versions, one for UTC and one for the user’s local time zone.
Core Characteristics
- Server-Side Only: GlideDateTime can only be used in server-side scripts (such as Business Rules, Script Includes, Workflow/Flow scripts, and Scheduled Scripts).
- UTC Storage: Under the hood, GlideDateTime stores date-time values in Coordinated Universal Time (UTC) / GMT.
- Timezone & Formatting Support: It handles automatic conversions between UTC storage, system time, and the user’s local time zone preferences.
GlideDateTime Methods & Example
GlideDateTime is a server-side ServiceNow API used to work with date and time values. It helps developers create date-time objects, add or subtract time, compare dates, and format date-time values.
Key GlideDateTime Methods
Arithmetic and Date-Time Operations
These methods help add or subtract time from an existing date-time value.
| Method | Description |
|---|---|
| add(Object time) | Adds a specified duration to the current date and time. |
| addSeconds(Number seconds) | Adds the specified number of seconds. |
| addDays(Number days) | Adds the specified number of days. |
| addMonths(Number months) | Adds the specified number of months. |
| addYears(Number years) | Adds the specified number of years. |
| subtract(Object time) | Subtracts a duration or another date-time value. |
Date and Time Comparison Methods
These methods help compare two date-time values and check which one is earlier or later.
| Method | Description |
|---|---|
| compareTo(GlideDateTime gdt) | Returns 0 if both dates are equal, 1 if the current date is later, and -1 if it is earlier. |
| before(GlideDateTime gdt) | Returns true if the current date-time is earlier than the given date-time. |
| after(GlideDateTime gdt) | Returns true if the current date-time is later than the given date-time. |
| onOrBefore(gdt) | Returns true if the current date-time is earlier than or equal to the given date-time. |
| onOrAfter(gdt) | Returns true if the current date-time is later than or equal to the given date-time. |
| equals(Object o) | Checks whether the current date-time matches another date-time value. |
Getting and Formatting Date-Time Values
These methods help retrieve date-time values and display them in different formats.
| Method | Description |
|---|---|
| getDisplayValue() | Returns the date and time in a user-friendly format based on the user’s preferences. |
| getNumericValue() | Returns the date-time value in milliseconds since January 1, 1970 (Unix epoch). |
| getByFormat(String format) | Returns the date and time in a specified format, such as yyyy-MM-dd HH:mm:ss. |
| convertTimeZone(String relFrom, String relTo) | Converts a date-time value from one time zone to another. |
GlideDateTime Examples in ServiceNow
Example 1: Creating an Object and Adding Days
var gdt = new GlideDateTime();
gs.info('Current Time: ' + gdt.getDisplayValue());
// Add 5 days
gdt.addDays(5);
gs.info('Time after 5 days: ' + gdt.getDisplayValue());
Example 2: Compare date and time using GlideDateTime
// Get the current date and time
var check = new GlideDateTime();
// Create start and end times for the current day
var start = new GlideDateTime(check);
start.setDisplayValue(check.getLocalDate() + " 08:00:00");
var end = new GlideDateTime(check);
end.setDisplayValue(check.getLocalDate() + " 17:00:00");
// Check whether the current time falls within working hours
if (check.onOrAfter(start) && check.before(end)) {
gs.info("Current time is inside the working window.");
} else {
gs.info("Current time is outside the working window.");
}
Example 3: Time Zone Conversion
var gdtEast = new GlideDateTime();
gdtEast.setValue('2026-01-01 12:00:00');
// Convert from UTC to EST / America/New_York
gdtEast.convertTimeZone('UTC', 'America/New_York');
gs.info('Converted Time: ' + gdtEast.getDisplayValue());
What is GlideAggregate?
GlideAggregate is a server-side API class in ServiceNow that extends GlideRecord. It is used to perform database-level calculations and summary operations such as COUNT, SUM, AVG, MIN, and MAX.
Unlike GlideRecord, which retrieves individual records, GlideAggregate asks the database to calculate the required result directly.
This makes it more efficient when working with large amounts of data because you don’t need to fetch and loop through thousands of individual records just to calculate a total.
GlideAggregate also supports GlideRecord query methods such as addQuery() and addEncodedQuery().
GlideAggregate Example: Count All Active Incidents
The following script uses GlideAggregate to count the total number of active incidents in ServiceNow.
var count = new GlideAggregate(‘incident’);
count.addQuery(‘active’, true);
count.addAggregate(‘COUNT’);
count.query();
if(count.next()){
var totalIncidents = count.getAggregate (‘COUNT’);
gs.info(‘Total : ‘ +totalIncidents);
}
GlideAggregate vs GlideRecord: When to Use Which
Both GlideRecord and GlideAggregate are server-side ServiceNow API classes used to query database records. However, they serve different purposes.
- GlideRecord is used to retrieve, create, update, and delete individual records.
- GlideAggregate is used to perform calculations such as counting records, finding averages, and calculating minimum or maximum values directly through database aggregation.
The main difference is that GlideRecord works with individual records, while GlideAggregate focuses on summary results. Choosing the right method can improve script performance, especially when working with large tables.
Difference Between GlideRecord and GlideAggregate
| Feature | GlideRecord | GlideAggregate |
|---|---|---|
| Main Purpose | Retrieves and manages individual records. | Performs calculations and summary operations on records. |
| Operations | Create, Read, Update, Delete (CRUD). | COUNT, SUM, AVG, MIN, MAX, etc. |
| Data Returned | Returns matching records with their field values. | Returns calculated results or grouped summary results. |
| Individual Record Access | Yes, you can access and modify individual records. | Mainly works with aggregate results and grouped fields. |
| Counting Records | Uses getRowCount() to count matching records. | Uses addAggregate(‘COUNT’) to count matching records efficiently. |
| Performance | Suitable when you need to work with individual records. | More efficient when you only need summary calculations. |
| Common Use Case | Updating incident priority or retrieving user details. | Counting active incidents or calculating average resolution time. |
When to Use GlideRecord
Use GlideRecord when you need to:
- Retrieve specific records from a table.
- Insert, update, or delete records.
- Read or modify individual field values.
- Apply conditions and perform operations on each matching record.
Example: When you want to find all active incidents and update their priority.
When to Use GlideAggregate
Use GlideAggregate when you need to:
- Count the total number of records in a table.
- Calculate the sum or average of numeric fields.
- Find the minimum or maximum value.
- Group records and generate summary results.
- Perform calculations on large datasets without retrieving every matching record.
Example: When you want to find the total number of active incidents or calculate the average incident resolution time.
Conclusion
Server-side scripting is an important part of ServiceNow development. This module covers the basics of server-side scripting, including the Glide classes and APIs behind it, GlideRecord query and CRUD methods, and how GlideSystem, GlideDateTime, and GlideAggregate help developers build reliable server scripts. Together, these ideas make it easier for developers to read and write clear, quick, and maintainable server-side scripts.
In the next chapter, we will focus on UI policies in ServiceNow, where you will learn how to control field behavior on a form without writing code and how to create a new UI policy step by step.
Need more support?
Get a head start with our FREE study notes!
Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.