Skip to main content
Jem123456
Participating Frequently
June 21, 2021
Answered

Ho do I calculate "Today - DOB = age in years" in a PDF?

  • June 21, 2021
  • 2 replies
  • 1874 views

I have found a Script that caluates age into months however I need age in years. How do I change the below script?

 

var cDateFormat = "dd-mmm-yyyy";
var cDate = this.getField("dob").value;
if(cDate != "") {
var oDate = util.scand(cDateFormat, cDate);
}
if(oDate == null) app.alert("Invalid date: " + cDate, 1, 0);

else {
var now = new Date();
var nMonth = Number(now.getMonth());
var nYear = Number(now.getFullYear());
var diffYear = nYear - oDate.getFullYear();
var diffMonth = nMonth-oDate.getMonth();
if (diffYear) {
diffYear = diffYear * 12;
}

event.value = diffMonth + diffYear;
}

This topic has been closed for replies.
Correct answer try67

In closer inspection, the code you used is incorrect, so I fixed it for you. Try this:

 

event.value = "";
var cDateFormat = "dd-mmm-yyyy";
var cDate = this.getField("dob").valueAsString;
if (cDate != "") {
	var oDate = util.scand(cDateFormat, cDate);
	if (oDate == null) app.alert("Invalid date: " + cDate, 1, 0);
	else {
		var now = new Date();
		var diffYear = now.getFullYear() - oDate.getFullYear();
		var diffMonth = now.getMonth()-oDate.getMonth();
		if (diffMonth<0) diffYear--;
		else if (diffMonth==0) {
			var diffDay = now.getDate()-oDate.getDate();
			if (diffDay<0) diffYear--;
		}
		event.value = diffYear;
	}
}

2 replies

try67
Community Expert
Community Expert
June 21, 2021

Divide the result by 12 and round down.

Jem123456
Jem123456Author
Participating Frequently
June 23, 2021

Hi Try67,

 

Where do I insert this into the above script?

 

try67
Community Expert
try67Community ExpertCorrect answer
Community Expert
June 23, 2021

In closer inspection, the code you used is incorrect, so I fixed it for you. Try this:

 

event.value = "";
var cDateFormat = "dd-mmm-yyyy";
var cDate = this.getField("dob").valueAsString;
if (cDate != "") {
	var oDate = util.scand(cDateFormat, cDate);
	if (oDate == null) app.alert("Invalid date: " + cDate, 1, 0);
	else {
		var now = new Date();
		var diffYear = now.getFullYear() - oDate.getFullYear();
		var diffMonth = now.getMonth()-oDate.getMonth();
		if (diffMonth<0) diffYear--;
		else if (diffMonth==0) {
			var diffDay = now.getDate()-oDate.getDate();
			if (diffDay<0) diffYear--;
		}
		event.value = diffYear;
	}
}
John Waller
Community Expert
Community Expert
June 21, 2021

Which Adobe application are you using?

Jem123456
Jem123456Author
Participating Frequently
June 23, 2021

Hi John,

Im using Adobe Acrobat DC