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.

Calculate Users Age based on Date of Birth

easybizit
Kilo Explorer

Hi Guys

I have created a custom app (Case Management Tool) and I have a have a requirement that I would be fairly simple, get the users age in years based on their date of birth. This is a scoped application, which changes the script you can use. So far I have developed a simple business rule:

(function executeRule(current, previous /*null when async*/) {

  var dateToday = new GlideDate(); // tried with and without .getDisplayValue()

  var d = new GlideDuration();

  d = GlideDate.subtract(dateToday,current.date_of_birth);

  gs.addInfoMessage(d.getDisplayValue());

})(current, previous);

I get this error:

Error running business rule 'Get Age on x_crcc_casetrack_v_client:CLI0001771, exception: org.mozilla.javascript.EvaluatorException: Can't find method com.glide.glideobject.GlideDateTime.subtract(com.glide.script.fencing.ScopedGlideDate,com.glide.script.glide_elements.GlideElementGlideObject). (sys_script.cbec1e6a4fe12e40a4cb0ed11310c72d; line 4)

On the surface it seems to not like the GlideDate.subtract call. Note sure if I'm going about this all the wrong way. At the moment I am placing the output into a info message but it will return to a text field when completed. Any suggestions?

1 ACCEPTED SOLUTION

jake_mckenna
ServiceNow Employee
ServiceNow Employee

Try something like what i have below. Using GlideDateTime functions normally are more helpful in doing something like you are trying. http://wiki.servicenow.com/?title=GlideDateTime#getYearLocalTime.28.29



(function executeRule(current, previous /*null when async*/) {


      var today = new GlideDateTime();


      var todayYear = today.getYearLocalTime();


      var bday = new GlideDateTime(current.date_of_birth.toString());


      bdayYear = bday.getYearLocalTime();


      var age = todayYear - bdayYear;


      gs.addInfoMessage(age);


})(current, previous);


View solution in original post

2 REPLIES 2

jake_mckenna
ServiceNow Employee
ServiceNow Employee

Try something like what i have below. Using GlideDateTime functions normally are more helpful in doing something like you are trying. http://wiki.servicenow.com/?title=GlideDateTime#getYearLocalTime.28.29



(function executeRule(current, previous /*null when async*/) {


      var today = new GlideDateTime();


      var todayYear = today.getYearLocalTime();


      var bday = new GlideDateTime(current.date_of_birth.toString());


      bdayYear = bday.getYearLocalTime();


      var age = todayYear - bdayYear;


      gs.addInfoMessage(age);


})(current, previous);


Yep, that works perfectly, thank you!