Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Client Script Date/Time Functions

MB26
ServiceNow Employee
ServiceNow Employee

This post started out with me trying to compare glide date/time fields via client scripts, which can be a bear. Since gs. is not available in the client, I was forced to come up with other methods of manipulating these fields via a client script. Using g_form.getNumericValue(), then parsing out the year, month, day, time etc. and putting that into a new Date() javascript object was one among many options I saw. However this method does not take into account differences in date/time formats.

The method I decided to use was Asynchronous Glide Ajax. Forget the "AJAXEvaluateSynchronously" function of the past. With GlideAjax you can query for information asynchronously not preventing the browser from continuing to respond, unlike the other. Big win! So I set out to build a "ClientDateTimeUtils" script include that a glideajax script could call.

I am hoping to continue to improve these scripts, add more functionality, etc. If you have any suggestions, please let me know. A common ClientDateTimeUtils script would be nice to have.

The actual script include can be way found below. These are the functions, and an associated glideajax examples, of what you can call with this.

  1. getNowDateTimeDiff

    This ajax function will allow you to calculate the date/time difference between a field on the form and the now date/time. You can specify a return type - "dttype" to get the result in seconds, minutes, hours, or days. See the comment below for the parameter values.


    var cdt = g_form.getValue('due_date'); //First Date/Time field
    var dttype = 'minute'; //this can be day, hour, minute, second. By default it will return seconds.

    var ajax = new GlideAjax('ClientDateTimeUtils');
    ajax.addParam('sysparm_name','getNowDateTimeDiff');
    ajax.addParam('sysparm_fdt', cdt);
    ajax.addParam('sysparm_difftype', dttype);
    ajax.getXML(doSomething);

    function doSomething(response){
    var answer = response.responseXML.documentElement.getAttribute("answer");
    alert(answer);
    }
  2. getDateTimeDiff

    This ajax function will allow you to send in two different glide date/time fields and return a calculation of their date/time difference in seconds, minutes, hours, or days.


    var cdt = g_form.getValue('due_date'); //First Date/Time field
    var sdt = g_form.getValue('expected_start'); //Second Date/Time field
    var dttype = 'minute'; //this can be day, hour, minute, second. By default it will return seconds.

    var ajax = new GlideAjax('ClientDateTimeUtils');
    ajax.addParam('sysparm_name','getDateTimeDiff');
    ajax.addParam('sysparm_fdt', cdt);
    ajax.addParam('sysparm_sdt', sdt);
    ajax.addParam('sysparm_difftype', dttype);
    ajax.getXML(doSomething);

    function doSomething(response){
    var answer = response.responseXML.documentElement.getAttribute("answer");
    alert(answer);
    }
  3. getDateTimeBeforeNow

    This ajax function will take a glide date/time field and return the amount of time till the now date/time. A positive number will represent prior to now, and negative will be how much time after now. This is pretty much a duplicate of the first one "getNowDateTimeDiff" but it gives you the opposite in positive, negative numbers. Positive = before, negative = after.


    var cdt = g_form.getValue('due_date'); //first Date/Time field
    var dttype = 'minute'; //this can be day, hour, minute, second. By default it will return seconds.

    var ajax = new GlideAjax('ClientDateTimeUtils');
    ajax.addParam('sysparm_name','getDateTimeBeforeNow');
    ajax.addParam('sysparm_fdt', cdt);
    ajax.addParam('sysparm_difftype', dttype);
    ajax.getXML(doSomething);

    function doSomething(response){
    var answer = response.responseXML.documentElement.getAttribute("answer");
    alert(answer);
    }
  4. getDateTimeBeforeNowBool

    This ajax function will return a true or false if the date/time field is before the now date/time. This made it simpler, rather than having to do more processing on the client side, just evaluate true/false. Makes it simple.


    var cdt = g_form.getValue('due_date'); //first Date/Time field

    var ajax = new GlideAjax('ClientDateTimeUtils');
    ajax.addParam('sysparm_name','getDateTimeBeforeNowBool');
    ajax.addParam('sysparm_fdt', cdt);
    ajax.getXML(doSomething);

    function doSomething(response){
    var answer = response.responseXML.documentElement.getAttribute("answer");
    alert(answer);
    }
  5. getNowDateTime

    This function returns the date and time of right now.


    var ajax = new GlideAjax('ClientDateTimeUtils');
    ajax.addParam('sysparm_name','getNowDateTime');
    ajax.getXML(doSomething);

    function doSomething(response){
    var answer = response.responseXML.documentElement.getAttribute("answer");
    alert(answer);
  6. getNowDate

    This function returns the date of right now.


    var ajax = new GlideAjax('ClientDateTimeUtils');
    ajax.addParam('sysparm_name','getNowDate');
    ajax.getXML(doSomething);

    function doSomething(response){
    var answer = response.responseXML.documentElement.getAttribute("answer");
    alert(answer);
  7. getNowTime

    This function returns the time of right now.


    var ajax = new GlideAjax('ClientDateTimeUtils');
    ajax.addParam('sysparm_name','getNowTime');
    ajax.getXML(doSomething);

    function doSomething(response){
    var answer = response.responseXML.documentElement.getAttribute("answer");
    alert(answer);
  8. addDateTimeAmount

    With this ajax function you can add more time to a glide date/time field. You can add seconds, minutes, hours, days, weeks, months, and years. If you want to take time away, use a negative number in the addtime variable.

    Limitation:

    One limitation that I have found so far is in the return date/time format. The added-to-time new date/time is returned in the standard internal date/time format. I am trying to figure out how to return it based on the user defined date/time format. Still a work in progress.



    var cdt = g_form.getValue('due_date'); //Choose the field to add time from
    var addtime = 3; //The amount of time to add
    var addtype = 'day'; //The time type.   Can be second, minute, hour, day, week, month, year.

    var ajax = new GlideAjax('ClientDateTimeUtils');
    ajax.addParam('sysparm_name', 'addDateTimeAmount');
    ajax.addParam('sysparm_fdt', cdt);
    ajax.addParam('sysparm_addtime', addtime);
    ajax.addParam('sysparm_addtype', addtype);
    ajax.getXML(doSomething);


    function doSomething(response){
          var answer = response.responseXML.documentElement.getAttribute("answer");
          //You could then take the new Date/Time answer and set the value of another field.
          // g_form.setValue('expected_start', answer);
          alert(answer);
    }
  9. addDateAmount

    This is a function to add time to a Glide Date field. You can add days, weeks, months, or years.


    var cdt = g_form.getValue('some_date'); //Choose the field to add time from
    var addtime = 3; //The amount of time to add
    var addtype = 'day'; //The time type.   Can be day, week, month, year.

    var ajax = new GlideAjax('ClientDateTimeUtils');
    ajax.addParam('sysparm_name', 'addDateAmount');
    ajax.addParam('sysparm_fdt', cdt);
    ajax.addParam('sysparm_addtime', addtime);
    ajax.addParam('sysparm_addtype', addtype);
    ajax.getXML(doSomething);


    function doSomething(response){
          var answer = response.responseXML.documentElement.getAttribute("answer");
          alert(answer);
    }
  10. addTimeAmount

    This is a function to add time to a Glide Time field. You can add seconds, minutes, hours.




    var cdt = g_form.getValue('some_time_field'); //Choose the field to add time from
    var addtime = 3; //The amount of time to add
    var addtype = 'day'; //The time type.   Can be second, minute, hour.

    var ajax = new GlideAjax('ClientDateTimeUtils');
    ajax.addParam('sysparm_name', 'addTimeAmount');
    ajax.addParam('sysparm_fdt', cdt);
    ajax.addParam('sysparm_addtime', addtime);
    ajax.addParam('sysparm_addtype', addtype);
    ajax.getXML(doSomething);


    function doSomething(response){
          var answer = response.responseXML.documentElement.getAttribute("answer");
          alert(answer);
    }


ClientDateTimeUtils Script Include Code
I have not found that there is any limitation with the date or time formats a user may use in the calculation of the dates/times on the server. I have tested each one of these in many different timezones and date/time formats with consistent success in their calculation. The only limitation that I have found is listed above in the "addDateTimeAmount" function. i.e. The returned date/time is in the standard internal format, not the user defined format. One other point of variation would be that all of my testing was done with Glide Date/Time fields. I have not tested merely Glide Date or Time fields.


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

//Takes a Single Date/Time Field and returns its time difference from nowDateTime().
//params = sysparm_fdt (the first date/time field), sysparm_difftype (time based format to return result. See "_calcDateDiff" function comments)
getNowDateTimeDiff: function(){
var firstDT = this.getParameter('sysparm_fdt'); //First Date-Time Field
var diffTYPE = this.getParameter('sysparm_difftype'); // Date-Time Type to return the answer as. Can be second, minute, hour, day
var diff = gs.dateDiff(gs.nowDateTime(), firstDT, true);
var timediff = this._calcDateDiff(diffTYPE, diff);
//return "getNowDateTimeDiff: FIRST DT: " + firstDT + " -DIFFTYPE: " + diffTYPE + " -TIME DIFF: " + timediff;
return timediff;
},

//Diff the amount of time between two different Date/Time fields
//params = sysparm_fdt (the first date/time field), sysparm_sdt (second date/time field), sysparm_difftype (time based format to return result. See "_calcDateDiff" function comments)
getDateTimeDiff: function(){
var firstDT = this.getParameter('sysparm_fdt'); //First Date-Time Field
var secondDT = this.getParameter('sysparm_sdt'); // Second Date-Time Field
var diffTYPE = this.getParameter('sysparm_difftype'); // Date-Time Type to return the answer as. Can be second, minute, hour, day
var diff = gs.dateDiff(firstDT, secondDT, true);
var timediff = this._calcDateDiff(diffTYPE, diff);
//return "getDateTimeDiff: FIRST DT: " + firstDT + " -SECOND DT: " + secondDT + " -DIFFTYPE: " + diffTYPE + " -TIME DIFF: " + timediff;
return timediff;
},

//Takes your date/time field and returns the amount of time before now. A positive is time before now, a negative number is after now.
//params = sysparm_fdt (the first date/time field), sysparm_difftype (time based format to return result. See "_calcDateDiff" function comments)
getDateTimeBeforeNow: function(){
var firstDT = this.getParameter('sysparm_fdt'); //First Date-Time Field
var diffTYPE = this.getParameter('sysparm_difftype'); // Date-Time Type to return the answer as. Can be second, minute, hour, day
var diff = gs.dateDiff(firstDT, gs.nowDateTime(), true);
var timediff = this._calcDateDiff(diffTYPE, diff);
//return "getDateTimeBeforeNow: FIRST DT: " + firstDT + " -DIFFTYPE: " + diffTYPE + " -TIME DIFF: " + timediff;
return timediff;
},

//Returns true if it is before now, and false if it is after now.
//params = sysparm_fdt (the first date/time field)
getDateTimeBeforeNowBool: function(){
var firstDT = this.getParameter('sysparm_fdt'); //First Date-Time Field
var diff = gs.dateDiff(firstDT, gs.nowDateTime(), true);
var answer = '';
if (diff >= 0){answer = 'true';}
else {answer = 'false';}
return answer;
},

//Returns the Date/Time of right now.
getNowDateTime: function(){
var now = gs.nowDateTime(); //Now Date/Time
return now;
},

//Returns the Date right now.
getNowDate: function(){
var now = GlideDate();; //Now Date
return now.getLocalDate();
},

//Returns the Time of right now.
getNowTime: function(){
var now = GlideTime();; //Now Time
var modnow = now.getLocalTime().toString().split(' ');
return modnow[1];
},

//Takes a date/time field and adds time to it.
//params = sysparm_fdt (the first date/time field), sysparm_addtype (type of time to add - second, minute, hour, day, week, month, year), sysparm_addtime (amount of time to add based on the type).
addDateTimeAmount: function(){
var firstDT = this.getParameter('sysparm_fdt'); //First Date-Time Field
var addTYPE = this.getParameter('sysparm_addtype'); //What to add - second (addSeconds()), minute (need to add conversion), hour (need to add conversion), day (addDays()), week (addWeeks()), month (addMonths()), year (addYears())
var addTIME = this.getParameter('sysparm_addtime'); //How much time to add
var day = GlideDateTime(firstDT);

if(addTYPE == 'second'){day.addSeconds(addTIME);}
else if (addTYPE == 'minute'){day.addSeconds(addTIME*60);}
else if (addTYPE == 'hour'){day.addSeconds(addTIME*(60*60));}
else if (addTYPE == 'day'){day.addDays(addTIME);}
else if (addTYPE == 'week'){day.addWeeks(addTIME);}
else if (addTYPE == 'month'){day.addMonths(addTIME);}
else if (addTYPE == 'year'){day.addYears(addTIME);}
else {day.addDays(addTIME);}

//return "First Date: " + firstDT + " -Time to Add: " + addTIME + " -Add Type: " + addTYPE + " -Added Time: " + day;
return day;
},

//Takes a glide date field and adds time to it.
//params = sysparm_fdt (the first date/time field), sysparm_addtype (type of time to add - day, week, month, year),sysparm_addtime (amount of time to add based on the type).
addDateAmount: function(){
var firstDT = this.getParameter('sysparm_fdt'); //First Date Field
var addTYPE = this.getParameter('sysparm_addtype'); //What to add - day (addDays()), week (addWeeks()), month (addMonths()), year (addYears())
var addTIME = this.getParameter('sysparm_addtime'); //How much time to add
var day = GlideDate();
day.setValue(firstDT);

if(addTYPE == 'day'){day.addDays(addTIME);}
else if (addTYPE == 'week'){day.addWeeks(addTIME);}
else if (addTYPE == 'month'){day.addMonths(addTIME);}
else if (addTYPE == 'year'){day.addYears(addTIME);}
else {day.addDays(addTIME);}

//return "First Date: " + firstDT + " -Time to Add: " + addTIME + " -Add Type: " + addTYPE + " -Added Time: " + day;
return day;
},

addTimeAmount: function(){
var firstDT = this.getParameter('sysparm_fdt'); //First Date-Time Field
var addTYPE = this.getParameter('sysparm_addtype'); //What
var addTIME = this.getParameter('sysparm_addtime'); //How much time to add
var time = GlideTime();
time.setValue(firstDT);

if(addTYPE == 'second'){time.addSeconds(addTIME);}
else if (addTYPE == 'minute'){time.addSeconds(addTIME*60);}
else if (addTYPE == 'hour'){time.addSeconds(addTIME*(60*60));}
else {time.addSeconds(addTIME);}

var modtime = time.toString().split(' ');
//return "First Date: " + firstDT + " -Time to Add: " + addTIME + " -Add Type: " + addTYPE + " -Added Time: " + time;
return modtime[1];
},

//Private function to calculate the date difference return result in second, minute, hour, day.
_calcDateDiff: function(diffTYPE, seconds){
var thisdiff;
if (diffTYPE == "day"){thisdiff = seconds/86400;}
else if (diffTYPE == "hour"){thisdiff = seconds/3600;}
else if (diffTYPE == "minute"){thisdiff = seconds/60;}
else if (diffTYPE == "second"){thisdiff = seconds;}
else {thisdiff = seconds;}
return thisdiff;
}


});

86 REPLIES 86

Thanks Sue!   I still can't get this to work.   I created the above script include in a scoped app, made it client callable, and accessible from all application scopes.   My Client Script is onSubmit and looks like this:



function onSubmit() {


    //Type appropriate comment here, and begin script below


var start = g_form.getValue('from');


var end = g_form.getValue('to');  


var dttype = 'year'; //this can be day, hour, minute, second. By default it will return seconds.  




var ajax = new GlideAjax('x_dnf_federal_hr_o.ClientDateTimeUtils');  


ajax.addParam('sysparm_name','getDateTimeDiff');  


ajax.addParam('sysparm_fdt', start);  


ajax.addParam('sysparm_sdt', end);  


ajax.addParam('sysparm_difftype', dttype);  


ajax.getXML(doSomething);  




function doSomething(response){  


var answer = response.responseXML.documentElement.getAttribute("answer");  


g_form.setValue('year', answer);


}        


}



Any advice on what's wrong here?        


I don't see anything obvious (but it is early morning here).



If you haven't done so already, I would recommend confirming the values of all the data that you're sending to the script include (I use alerts to do this.)


Then I'd add log statements to your script include to see if it's being reached at all.



We've seen the occasional error where the value you're passing actually turns out to be a different type than the one you need.


True, I am also getting the 'null' in scoped application. 

I want to check with current time with a value stored in a date/time field. SO I am using 'getNowDateTimeDiff'. 

I checked in plain instance. It is working super. Thank you. 

But in grc scoped application, I changed it to 'globalAbstractAjaxProcessor' but I am getting 'null' in 'answer'. Any idea why?

jas101
Tera Expert

Hi all, really hope someone is able to help as I would love to get this working.

Basically on our CHG form Schedule tab we have the OTB date/time fields: 'Planned start' and 'Planned end'

We want to add a field for 'change duration', so this would then get added to the 'Planned start' in order to automatically set value 'Planned end' (which we would then make read-only).

I have created the above script include and have created a corresponding onChange client script but the value is not being set and the alert is always saying 'null'.

Also I'm not sure what the best field type is for our new 'change duration' field - ideally we'd want the user to specify in hours. I've tried string, decimal and duration type fields. One which is able to force a consistent format would obviously be preferred.

Current client script is below (the onChange field name is set to 'Duration 2'). I know it currently says minutes, I have played with this in attempt to get it working also.

Many thanks for any help in advance,

DS

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
   if (isLoading || newValue === '') {
      return;
   }

   //Type appropriate comment here, and begin script below
      var sdt = g_form.getValue('start_date'); //Choose the field to add time from  
      var addtime = g_form.getValue('u_duration_2'); //The amount of time to add  
      var addtype = 'minute'; //The time type.   Can be second, minute, hour, day, week, month, year.  
var ajax = new GlideAjax('ClientDateTimeUtils');  
      ajax.addParam('sysparm_name', 'addDateTimeAmount');  
ajax.addParam('sysparm_fdt', sdt);  
ajax.addParam('sysparm_addtime', addtime);  
ajax.addParam('sysparm_addtype', addtype);  
ajax.getXML(doSomething);  
 
  function doSomething(response){  
      var answer = response.responseXML.documentElement.getAttribute("answer");  
      //You could then take the new Date/Time answer and set the value of another field.  
      g_form.setValue('end_date', answer);
g_form.setReadOnly('end_date', 'true');
       
      alert(answer);  
}
}

benn23
ServiceNow Employee
ServiceNow Employee

Have you tried adding logs to the 'addDateTimeAmoun' function within that script include?  Just to ensure that the parms are making it from the client to the server.