How to calculate user Age based on 2 date fields using a Scope App?

cms1
Tera Contributor

I have two date fields on a scoped app, those are: u_received_date , u_dob

Subtracting these values will tell me the age of the user at the time the request was received. 

I have created the following Business Rule but it doesn't calculate the age correctly.

For example, 

If the received date = 07/10/18 and the date of birth = 08/18/1979 the value being populated is 39 and it should be 38. Please see my code below any help will be appreciated.

(function executeRule(current, previous /*null when async*/) {
var recDa = new GlideDateTime(current.u_received_date.getDisplayValue());
var recDaYear = recDa.getYearLocalTime();

var bday = new GlideDateTime(current.u_dob.getDisplayValue());
bdayYear = bday.getYearLocalTime();
var age = recDaYear - bdayYear;

//gs.addInfoMessage(age);
current.u_age = age;
})(current, previous);

1 ACCEPTED SOLUTION

Hi,

Please mark this as "Correct Answer" if I have given you a sufficient answer and you have no other questions.

Best Regards,
Daniele

View solution in original post

8 REPLIES 8

Daniele Songini
Tera Guru

Hi,
try this

var sgd1 = new GlideDate(); 
var sgd2 = new GlideDate();

sgd1.setDisplayValue('2014-07-18'); 
sgd2.setDisplayValue('2014-07-19'); 

duration= GlideDate.subtract(sgd1, sgd2); 

duration = parseInt(duration.getDisplayValue()/100*60*24*365); // Years

Please mark this as "Correct Answer" if I have given you a sufficient answer to your question.

Best Regards,
Daniele

Daniele Songini
Tera Guru

Hi,

Try this, it works for me

var sgd1 = new GlideDate(); 
var sgd2 = new GlideDate();

sgd1.setDisplayValue( '11-07-2018' ); 
sgd2.setDisplayValue( '23-07-2018' ); 

duration = GlideDate.subtract( sgd1, sgd2 ).getDayPart(); 
duration = parseInt( duration / 365 ); // Years

subtract return a GlideDuration

Please mark this as "Correct Answer" if I have given you a sufficient answer to your question.

Best Regards,
Daniele

unfortunately the GlideDate does not work in scoped app

 

sopan kale
Kilo Expert

Hi,

 

PFB the code for "after" BR

 

 

var startDate = current.u_date1.getGlideObject();
var endDate = current.u_date2.getGlideObject();

var age = gs.dateDiff(startDate.getDisplayValue(),endDate.getDisplayValue(),true);
gs.addInfoMessage("age is"+age);

var yr=age /(60*60*24*365);

var s=yr.toString().split(".");

gs.addInfoMessage("age is"+s[0]);

 

this will fulfill your requirement.

 

Please mark reply as Helpful/Correct, if applicable. Thanks!

Warm Regards,

sopan kale

find_real_file.png
www.dxsherpa.com