Calculating Person's Age from Date Field

Brett14
Giga Expert

All,

I have been on the forum getting examples to populate a 'string' field called age to display the age of the person filling out the catalog item.   I have a Date variable and when they type in or select from calendar the 'age' string field should populate with their age.

I have created a script include and a client script that calls it, but my issue is that how do I get rid of the decimal in my string field?   Is it due to only using a date variable instead of a date/time variable.   I have copied my scripts below:

Any suggestions would help me out.

Script Include:

var AjaxGetAge = Class.create();

AjaxGetAge.prototype = Object.extendsObject(AbstractAjaxProcessor, {

birthCalc: function() {

  var db = new GlideDateTime(this.getParameter('sysparm_strt'));

  var datebirth =   gs.dateDiff(db,gs.nowDate(), true);

  gs.log('Difference: '+datebirth);

  var seconds = parseInt(datebirth, 10);

  var whole = seconds/(365*24*3600);

  var convert = Math.floor(whole);

  gs.log('Years: '+convert);

  return convert;

}

});

Client Script:

function onChange(control, oldValue, newValue, isLoading) {

var birth = g_form.getValue('date_of_birth');//set this as purchase date

var ajax = new GlideAjax('AjaxGetAge');

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

ajax.addParam('sysparm_strt',birth);

//ajax.addParam('sysparm_end',end);

ajax.getXMLWait();

var answer = ajax.getAnswer();

g_form.setValue('age', answer);

}

Screenshot of output on catalog item

find_real_file.png

1 ACCEPTED SOLUTION

Robert Chrystie
ServiceNow Employee
ServiceNow Employee

Hi Brett,



You could use .toPrecision(#) to set this.   Hopefully, this example will help explain.


View solution in original post

7 REPLIES 7

Robert Chrystie
ServiceNow Employee
ServiceNow Employee

Hi Brett,



You could use .toPrecision(#) to set this.   Hopefully, this example will help explain.


Hi Robert,



This worked great.   Thank you


djoodjii
Kilo Expert

Hi Brett,


g_form.setValue('age', answer.toPrecision(2));


djoodjii
Kilo Expert

you can use also Math.trunc(answer);instade of toPrecision cause if you have someone with more than 99 years you have to change the precision.



enjoy it