Time Conversion between timezone

Ranjit Nimbalka
Mega Sage

I have an requirement basically i need script which will convert 9AM UTC time to equivalent to different time zones.

Lets say user having time zone as "Europe" so need there time when UTC time is 9AM. we have lot of time zones so script should run for all based on user time zone.

 

Thanks

5 REPLIES 5

Jake Sadler
Kilo Sage

Hi @Ranjit Nimbalka ,

 

This should GlideDateTime method will return the users time.

 

var gdt = new GlideDateTime();

gdt.getLocalTime();

 

Thanks

 

Jake

Rajesh Chopade1
Mega Sage

Hi @Ranjit Nimbalka 

To achieve this in ServiceNow, you can use the GlideDateTime class,

Here's a script that will take a 9 AM UTC time and convert it to the equivalent time in various user time zones defined in ServiceNow.

 

Steps:

  1. Fetch all users and their respective time zones.
  2. Convert the 9 AM UTC time to the user's time zone.
  3. Output the results.

 

(function() {
    // Define the 9 AM UTC time
    var utcTime = new GlideDateTime();
    utcTime.setDisplayValue('2024-08-02 09:00:00');
    utcTime.setTZ('UTC');

    // GlideRecord to get all users
    var userGr = new GlideRecord('sys_user');
    userGr.query();
    
    while (userGr.next()) {
        // Get user's time zone
        var userTimeZone = userGr.time_zone.toString();
        if (!userTimeZone) {
            userTimeZone = 'UTC'; // Default to UTC if no time zone is set
        }

        // Convert UTC time to user's time zone
        var userTime = new GlideDateTime(utcTime);
        userTime.setTZ(userTimeZone);
        var userLocalTime = userTime.getDisplayValue();

        // Output the user's name, time zone, and the converted time
        gs.log('User: ' + userGr.name + ', Time Zone: ' + userTimeZone + ', Local Time: ' + userLocalTime);
    }
})();

 

I hope my answer helps you to resolve your issue if yes, mark my answer helpful & correct

THANK YOU

rajesh chopade

Hi @Rajesh Chopade1 ,

The function 

.setTZ

is not working into Background script.

you should be able to use .setTimeZone() instead.