Skip to content

Commit 5ca3180

Browse files
authored
Convert UTC time to local time (#1892)
* script.js * readme.md
1 parent f900211 commit 5ca3180

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
## Overview
2+
This script converts a UTC date/time field in ServiceNow to the local time of the user that the script runs under using GlideDateTime.
3+
This distinction is important in certain contexts, such as asynchronous business rules, scheduled jobs, or background scripts, where the executing user may differ from the record owner.
4+
It is useful for notifications, reports, dashboards, or any situation where users need localized timestamps that reflect the correct timezone.
5+
6+
## Table and Field Example
7+
Table: incident
8+
Field: opened_at (stored in UTC)
9+
10+
## How It Works
11+
The script queries the incident table for the most recent active incident.
12+
Retrieves the opened_at field (in UTC).
13+
Creates a GlideDateTime object to convert this UTC timestamp into the local time of the executing user.
14+
Logs both the original UTC time and the converted local time.
15+
16+
## Key Notes
17+
Conversion is always based on the timezone of the user executing the script.
18+
In asynchronous operations (background scripts, scheduled jobs, async business rules), this is the system user running the script.
19+
20+
## Reference
21+
https://developer.servicenow.com/dev.do#!/reference/api/zurich/server_legacy/c_GlideDateTimeAPI
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
(function() {
2+
var gr = new GlideRecord('incident');
3+
gr.addQuery('active', true);
4+
gr.orderByDesc('opened_at');
5+
gr.setLimit(1); // Example: take the latest active incident
6+
gr.query();
7+
8+
if (gr.next()) {
9+
// GlideDateTime object from UTC field
10+
var utcDateTime = gr.opened_at;
11+
12+
// Convert to user's local time zone
13+
var localTime = new GlideDateTime(utcDateTime);
14+
var displayValue = localTime.getDisplayValue(); // Returns local time in user's timezone
15+
16+
gs.info('UTC Time: ' + utcDateTime);
17+
gs.info('Local Time: ' + displayValue);
18+
} else {
19+
gs.info('No active incidents found.');
20+
}
21+
})();

0 commit comments

Comments
 (0)