Page 1 of 1

Calculate the age

Posted: Thu Jan 05, 2023 12:13 am
by yvesf
Hello,


I have date of birth and I would like to calculate the age in a calc field. Is it possible ? I have tried with the following script :

Code: Select all

function ageCalc(birth,age_num) {
let o = $('#' + birth);
let d = nuFORM.removeFormatting(o.val(), o.attr('data-nu-format'));
 var dob = new Date(d);  
    //calculate month difference from current date in time  
    var month_diff = Date.now() - dob.getTime();  
      
    //convert the calculated difference in date format  
    var age_dt = new Date(month_diff);   
      
    //extract year from date      
    var year = age_dt.getUTCFullYear();  
      
    //now calculate the age of the user  
    var age = Math.abs(year - 1970);  
console.log('age='+age);
nuSetvalue('age_num',age); 

} 
I have 2 fields pa_birthdate (date field with format yyyy-mm-dd) and pa_age(input field number )
I call this func as following

Code: Select all

ageCalc('pa_birthdate','pa_age');
It doesn't work for some reason. Anyone could help ?

Thanks,


Yves

Re: Calculate the age

Posted: Thu Jan 05, 2023 1:55 am
by yvesf
Pb solved. Help no longer needed for this script which works as expected. It was a typo with nuSetvalue() instead of nuSetValue() function.
The corrected function is :

Code: Select all

function ageCalc(birth,age_num) {
let o = $('#' + birth);
let d = nuFORM.removeFormatting(o.val(), o.attr('data-nu-format'));
 var dob = new Date(d);  
    //calculate month difference from current date in time  
    var month_diff = Date.now() - dob.getTime();  
      
    //convert the calculated difference in date format  
    var age_dt = new Date(month_diff);   
      
    //extract year from date      
    var year = age_dt.getUTCFullYear();  
      
    //now calculate the age of the user  
    var age = Math.abs(year - 1970);  
console.log('age='+age);
nuSetValue('age_num',age); 

} 
To be put in the setup header of the application as it is used everywhere.