logo

NJP

How to populate callers' current local time based on their time zone

Import · May 27, 2022 · article

Hi Everyone,

Sometimes we come across a requirement where we want to know selected users or callers' local time in case they have different time zones. So to overcome this issue, we can create an onLoad or Onchange client script to know their local time as below:

Here is an example of Onload client script on Incident table, where callers' local time gets populated as the Field Message.

Client Script:

function onLoad() {

    //Type appropriate comment here, and begin script below
    var gajax = new GlideAjax('MyFavoritesAjax');
    gajax.addParam('sysparm_name', 'getCallersLocalTime');
    gajax.addParam('sysparm_caller', g_form.getValue('caller_id'));
    gajax.getXML(getResults);

}

function getResults(response) {
    var answer = response.responseXML.documentElement.getAttribute("answer");
    //alert(answer);
    g_form.showFieldMsg('caller_id', answer, 'info');
}

Script Include : (Client Callable)

var MyFavoritesAjax = Class.create();
MyFavoritesAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    getCallersLocalTime: function() {
        var id = this.getParameter('sysparm_caller');

        var callerObject = new GlideRecord('sys_user');
        if (callerObject.get(id)) {

            //gs.info("current callers TZ : " + callerObject.time_zone);
            var time = new GlideDateTime();
            var tz = Packages.java.util.TimeZone.getTimeZone(callerObject.getValue('time_zone'));
            time.setTZ(tz);
            // Get offset of timezone set above  
            var timeZoneOffSet = time.getTZOffset();
            // Add offset to current time  
            time.setNumericValue(time.getNumericValue() + timeZoneOffSet);
            gs.info("Local time is : " + time); // prints Local Date time as : 2022-05-25 11:47:34 
            return time.toString();
        }

    },

    type: "MyFavoritesAjax"

});

Result :

Fred Luddy : US/Pacific

image

Beth Anglin : Canada/Mountain

image

Sam Sorokin : US/Eastern

image

Kindly mark it as helpful if applicable.

Please feel free to add comments if there are any improvements or suggestions.

View original source

https://www.servicenow.com/community/itsm-articles/how-to-populate-callers-current-local-time-based-on-their-time/ta-p/2306701