The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Calculate Age from DoB

mikey97
Tera Contributor

Hello, 

 

After searching for suggestions on the community I ended up with the following Script and Include:

 

Client Script: 

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

   //Type appropriate comment here, and begin script below
var ga = new GlideAjax('CarRentalUtils');
ga.addParam('sysparm_name','checkAge');
ga.addParam('sysparam_id',newValue);
ga.getXML(Process);
}
function Process(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
alert(answer);
var a = parseInt(answer);
alert(a);
g_form.setValue("u_age",a);
}
 
 
Script Include:
checkAge: function() {
        var dob = this.getParameter('sysparam_id');//param from client script
        var today = new GlideDateTime();
        var todayYear = today.getYearLocalTime();
        var bday = new GlideDateTime(dob.toString());
        var bdayYear = bday.getYearLocalTime();
        var age = todayYear - bdayYear;
        return age;
    },
 
 
It alerts me with "0" whenever I try to select a date and I can't figure it out.
 
Best regards,
Mike
1 ACCEPTED SOLUTION

Dibyaratnam
Tera Sage

Replace the lines "var dob =" & 2nd "ga.addParam(" with below lines. it should be sysparm_<anyName> and not sysparam_<anyName>. Now check what are you getting.

var dob = this.getParameter('sysparm_id');//param from client script
ga.addParam('sysparm_id',newValue);

 

View solution in original post

3 REPLIES 3

Dibyaratnam
Tera Sage

Replace the lines "var dob =" & 2nd "ga.addParam(" with below lines. it should be sysparm_<anyName> and not sysparam_<anyName>. Now check what are you getting.

var dob = this.getParameter('sysparm_id');//param from client script
ga.addParam('sysparm_id',newValue);

 

It’s working ! Thank you

Community Alums
Not applicable

Hi @mikey97 ,

 

Be careful - your script will not calculate someone's age correctly based on the year alone. If I was born on 27th January 2000, even though I would be 23 today (26th Jan), your code would return 24.

 

You also need to determine if the current month and day is prior to the birthday month and day, and take one off the age if so.

 

This function works correctly:

 

calculateAge: function(dob) {
 
// Get DoB
var gd1 = new GlideDate();
gd1.setValue(dob);
var yr1 = gd1.getByFormat("yyyy");
var mon_day1 = gd1.getByFormat("MMdd");
 
// Get Now
var gd2 = new GlideDate();
var yr2 = gd2.getByFormat("yyyy");
var mon_day2 = gd2.getByFormat("MMdd");
 
// Calculate age
var age = yr2 - yr1;
if (mon_day2 < mon_day1)
age --;
 
return age;
}