You are currently viewing How to get current date time using client script in ServiceNow?

How to get current date time using client script in ServiceNow?

Many times we need a date time at the client side in servicenow. There are many ways we can get it i.e. using JavaScript or using glide objects.

[youtube-feed feed=1][youtube-feed feed=3][youtube-feed feed=4]
My ServiceNow YouTube Channels

Use JavaScript Functions directly

//Get date time of system using JavaScript

function onLoad() {
    var date = new Date();
    alert(date);
}
//Output
Sun Nov 13 2022 20:37:27 GMT+0530 (India Standard Time)

This date object contains all date objects and there are various functions available to get separate things such as year, date etc. etc.

Use ServiceNow Glide System class functions

In this case, we can use servicenow out of the box class(glide system) and use its functions to get the value of the date and other items. This would require a calling script to include from the client side and return values of date and time.

The Glide System(gs) class works on the server side that’s why we have to do this whole process of calling script including using GlideAjax.

Client script:
var ajax = new GlideAjax('ClientDateTimeUtils');
ajax.addParam('sysparm_name','getNowDateTime');
ajax.getXML(DateTimeParser);
function DateTimeParser(response){
var answer = response.responseXML.documentElement.getAttribute("answer");
alert(answer);

Script Include:
var ClientDateTimeUtils = Class.create();
ClientDateTimeUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getNowDateTime: function(){
var now = gs.nowDateTime(); //Now Date/Time
return now;
},
    type: 'ClientDateTimeUtils'
});

//Output
13/11/2022 10:57:37

The output is the current date & time. I would recommend you use this script for all kinds of date & time functions for other tables as well.

Leave a Reply