Skip to main content
Yeep0104
Participant
April 24, 2022
Question

Calculating Age Between to dates with leap years taken into consideration

  • April 24, 2022
  • 1 reply
  • 766 views

Hello,

I know this question has been asked before and there are really great examples out there, however, I am new to writing scripts and am having trouble with getting leap years to be calculated between two dates. I am using the JavaScript Editor through Adobe from the Text Field Properties/Calculate/ Custom Calculation Script. 

 

I needed to determine the age between "Date of Filing" and "Date of Birth" and to auto-populate, in the "Age of Form Filing". I was successfully able to do so by using the following script below. However, it fails to take into account leap years. For instance, if I put in DOB as "01/01/2001" and the date of filing as "12/28/2022" It gives me the wrong age.  I have looked at other examples but I think I am too much of a novice to understand and fill in missing areas in the examples I have found or have been provided. I would really appreciate assistance with this. 

 

//Custom calculation script to calculate age based on date of birth and filing

 

var birth = this.getField("Date_of_Birth").value;

 

var form = this.getField("Date_Filing").value;

 

if (birth.length && filing.length) {

 

    var dateBirth = util.scand("mm/dd/yyyy", birth);

 

    var dateFiling = util.scand("mm/dd/yyyy", form);

 

//Calculate the difference in milliseconds

 

    var diff = (dateFiling.valueOf() - dateBirth.valueOf())/1000;

 

///Calculate years

 

var age = (((diff / 60) / 60) / 24) / 365;

 

// Round off the total using util.printf() method

 

event.value = util.printf("%0.0f", age);

 

}

 

Here are the examples that I have looked at and tried using:

 

if (HasValue(Date_of_Birth) and HasValue(Date_Form)) then

var Date_Form_= Date2Num(Date_Form.formattedValue, “MM/DD/YYYY”)

var Date_of_Birth_= Date2Num(Date_of_Birth.formattedValue, “MM/DD/YYYY”)

var diff = Date_Form_- Date_of_Birth_

var years = Floor(diff / 365.25)

var months = Floor(((diff / 365.25) - Floor(diff/ 365.25)) * 15.21

$ = Concat(years, “ years ”, months, “months.”)

else

$ = null

endif

 

and;

 

var birth = this.getField("Date_of_Birth").value;

 

var form = this.getField("Date_Form").value;

 

if (birth.length && form.length) {

 

    var dateBirth = util.scand("mm/dd/yyyy", birth);

 

    var dateForm = util.scand("mm/dd/yyyy", form);

 

function calAgeAtDate(birth, form) {

 

var age = form.getFullYear() - birth.getFullYear();

 

if (form.getMonth() < birth.getMonth()) {

age --;

} else if (form.getMonth()==birth.getMonth() && form.getDate() < birth.getDate())

{

age --;

}

return age;

}

 

This topic has been closed for replies.

1 reply

Bernd Alheit
Community Expert
Community Expert
April 25, 2022

Try the forum for Adobe Acrobat.