Getting Current Time for different Timezones

deepak50
Tera Contributor

Hi,

How Can I get the Current time for different timezones in script include.

For eg Current time in EST/PST/US Mountain etc. User can have any timezone setting in Profile like EST or PST but script should always give current time based on Timezone name passed.

I am working in scoped app and using below api

 

GlideScheduleDateTime(gdt).convertTimeZone(Timezone1 , TimeZone2);

 

But this is giving correct result only if user has Timezone setting in profile as GMT , It is failing is user has timezone setting as EST or PST in profile.

 

Thanks

Deepak

5 REPLIES 5

Riya Verma
Kilo Sage
Kilo Sage

Hi @deepak50 ,

Hope you are doing great.

 

To achieve this, we can create a custom script include that takes the timezone name as an input parameter and returns the current time based on the specified timezone.

 

// Custom script include: TimezoneUtil
var TimezoneUtil = Class.create();

TimezoneUtil.prototype = {
  initialize: function() {},

  getCurrentTimeByTimezone: function(timezone) {
    var currentTime;
    var gdt = new GlideDateTime(); // Get the current date and time in GMT.

    // Convert the current time to the specified timezone.
    if (timezone) {
      try {
        var timeZoneGMT = gs.getTimeZone(); // Get the user's timezone setting in GMT.
        gs.setTimeZone(timezone); // Set the timezone based on the input parameter.
        currentTime = new GlideDateTime(gdt).getLocalTime(); // Convert to the specified timezone.
        gs.setTimeZone(timeZoneGMT); // Reset the timezone back to the user's original setting.
      } catch (e) {
        gs.error("Error while converting time to timezone: " + timezone);
      }
    }

    return currentTime;
  },

  type: 'TimezoneUtil'
};

 

 
Please mark the appropriate response as correct answer and helpful, This may help other community users to follow correct solution.
Regards,
Riya Verma