Find your people. Pick a challenge. Ship something real. The CreatorCon Hackathon is coming to the Community Pavilion for one epic night. Every skill level, every role welcome. Join us on May 5th and learn more here.

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

cms1
Tera Contributor

Unfortunately I can not use dateDiff in a scoped app 😞

cms1
Tera Contributor

Thank you everyone - I was able to get the following to work using Scoped app: 

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

var gdt1 = new GlideDateTime(current.u_received_date.getDisplayValue());
var gdt2 = new GlideDateTime(current.u_dob.getDisplayValue());

duration = GlideDateTime.subtract( gdt2, gdt1 ).getDayPart();
duration = parseInt( duration / 365 ); // Years

//gs.addInfoMessage(duration);
current.u_age = duration;

})(current, previous);

Hi,

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

Best Regards,
Daniele

cms1
Tera Contributor

FYI - I also did the following: 

current.u_age = duration.toPrecision(2);  //added to avoid the decimal point