Populate UTC Time based on the current timezone of the user
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-29-2025 06:03 AM - edited ‎07-29-2025 06:04 AM
I have a requirement to populate the UTC time in a catalog item variable based on the user's timezone and the current time. If the current time changes UTC timing should be adjusted automatically. My script is running fine when we are entering the username for the 1st time, then if we change the current time then UTC time is not getting adjusted and returning "null"
Script Include
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-29-2025 06:10 AM
try this
Client Script:
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
var UTC = g_form.getValue('current_time');
var userId = g_form.getValue('affected_user');
// Basic validation
if (!userId || !UTC) {
return;
}
var ga = new GlideAjax('GetAffectedUserTime');
ga.addParam('sysparm_name', 'getUTCtime');
ga.addParam('sysparm_utc', UTC);
ga.addParam('sysparm_user_id', userId);
ga.getXMLAnswer(function(response) {
if (response) {
g_form.setValue('utc_time', response);
} else {
g_form.setValue('utc_time', '');
}
});
}
Script Include:
getUTCtime: function() {
var userID = this.getParameter('sysparm_user_id');
var localTime = this.getParameter('sysparm_utc'); // time sent by client, assumed local
var gr = new GlideRecord('sys_user');
if (!gr.get(userID) || !localTime) {
return '';
}
var userTimeZone = gr.time_zone;
var gdt = new GlideDateTime();
// Parse incoming datetime string as user local time
// Assumes localTime is in format "yyyy-MM-dd HH:mm:ss"
gdt.setDisplayValue(localTime, userTimeZone);
// Now switch gdt to UTC timezone
gdt.setTimeZone('UTC');
// Return UTC time string
return gdt.getDisplayValue();
}
If my response helped please mark it correct and close the thread so that it benefits future readers.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-29-2025 07:35 AM
Hi,
I updated the script but now it is giving some random timing, not the correct UTC time
System Admin's timezone is Europe/Paris so it is showing wrong timing here
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-29-2025 09:23 PM
what debugging did you do?
did you see if script include is running? what came in logs?
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader