These forums are now Read Only. If you have an Acrobat question, ask questions and get help from one of our experts.

Calculate age in javascript

beaumisbro
Registered: Apr 6 2009
Posts: 14
Answered

hello all,

i can use some help of the experts here, i'm working on a pdf where i want to calculate the age of a person based on the DOB they enter, i also have the user enter the current date in a separate field. can someone help in creating a javascript that i can use to calculate the age??

thanks for your help.

-Andy

My Product Information:
Acrobat Pro 8.1.2, Windows
gkaiseril
Expert
Registered: Feb 23 2006
Posts: 4307
Have you tired the search feature?

George Kaiser

beaumisbro
Registered: Apr 6 2009
Posts: 14
yes i've been trying to locate an existing post but in vain. i found only one but that was in Livecycle designer.
try67
Expert
Registered: Oct 30 2008
Posts: 2398
Make a new Date object. It will point to "now". Reduce the birth year from now's year. If the birth month is higher then now's month, reduce one year from the result. If it's the same month and the birth date is higher then now's date, reduce one year from the result.

- AcrobatUsers Community Expert - Contact me personally at try6767 [at] gmail [dot] com
Check out my custom-made scripts website: http://try67.blogspot.com

beaumisbro
Registered: Apr 6 2009
Posts: 14
thanks for the reply bud, though im not quite sure if i follow you. ok so i've made a new text field and changed its format to date, how do i point it to "now". and whats the procedure to reduce the birth yr from now's yr??
the nOOb thanks you for your kind responses.

-A
try67
Expert
Registered: Oct 30 2008
Posts: 2398
No, not a text field. You need to create a Date object. It's a built-in feature of JavaScript.
You can read more about it here: http://w3schools.com/jsref/jsref_obj_date.asp

- AcrobatUsers Community Expert - Contact me personally at try6767 [at] gmail [dot] com
Check out my custom-made scripts website: http://try67.blogspot.com

gkaiseril
Expert
Registered: Feb 23 2006
Posts: 4307
You can also look at [url=http://www.acrobatusers.com/tutorials/2006/date_time_part2/]Working with date and time in Acrobat JavaScript (part 2 of 3)[/url] and see how to compute the number of days between 2 dates, but instead of useing the number of milliseones for one day, use the value for 365.25 time the value for one day.

George Kaiser

beaumisbro
Registered: Apr 6 2009
Posts: 14
this is what i came up with but since this is my first attempt at programming/scripting it doesnt seem to work. please advise.
"DOB" is the cell name for date of birth entered by user, "Age" is the calculated field, and "Today" is the current date entered by the user.

var strStart = this.getField("DOB").value;
var strEnd = this.getField("Today").value;
if(strStart.length || strEnd.length)
{
var dob = util.scand("mmm d, yyyy",strStart);var today = util.scand("mmm d, yyyy",strEnd);
var diff = today.getTime() - dob.getTime();
var oneyr = 365.25 * 24 * 60 * 60 * 1000
var age = Math.floor(diff/oneyr);
}
gkaiseril
Expert
Registered: Feb 23 2006
Posts: 4307
You have not set any field to the age value. The code for the field "Age" could read:
// define some time constantsvar fSec = 1000; //secondvar fMin = 60 * fSec; // minutevar fHr = 60 * fMin; // hourvar fDay = 24 * fHr; // dayvar fYear = 365.25 * fDay; // year var strStart = this.getField("DOB").value; // dob// var strToday = util.printd("mmm dd, yyyy", new Date()); // get system date timevar strToday = this.getField("Today").value;// compute if there are values for dob and todayif(strStart.length & strToday.length) {var dob = util.scand("mmm d, yyyy", strStart); // convert dob to date time objectvar today = util.scand("mmm d, yyyy", strToday); // convert today to date time objectvar diff = today.valueOf() - dob.valueOf();  // compute difference of valuesdiff = diff + fDay; // adjust to count today as a counted dayevent.value = Math.floor(diff/ fYear); // truncate to whole years}

George Kaiser

beaumisbro
Registered: Apr 6 2009
Posts: 14
wow this works beautifully, thank you so very much!!!!!! thank you everyone for their kind inputs.
rrwester
Registered: Oct 8 2009
Posts: 7
It's amazing that SO MANY of my searches and SUCCESSFUL solutions have coincidentally been associated with "gkaiseril". I envy this man's knowledge of Acrobat! The "Try67" posts have been beneficial also.

Anyway, I know I have to be close utilizing the code below on my form.
I have a DOB field the user enters. It is date formatted as mm/dd/yyyy
I have a field titled PATIENTS_AGE that I have checkmarked as read only, visible, and entered the Custom Calculation Java Script exactly as shown by my new-found hero.

So, why will the age not display once I have entered the DOB and hit tab?

gkaiseril wrote:
You have not set any field to the age value. The code for the field "Age" could read:
// define some time constantsvar fSec = 1000; //secondvar fMin = 60 * fSec; // minutevar fHr = 60 * fMin; // hourvar fDay = 24 * fHr; // dayvar fYear = 365.25 * fDay; // year var strStart = this.getField("DOB").value; // dob// var strToday = util.printd("mmm dd, yyyy", new Date()); // get system date timevar strToday = this.getField("Today").value;// compute if there are values for dob and todayif(strStart.length & strToday.length) {var dob = util.scand("mmm d, yyyy", strStart); // convert dob to date time objectvar today = util.scand("mmm d, yyyy", strToday); // convert today to date time objectvar diff = today.valueOf() - dob.valueOf();  // compute difference of valuesdiff = diff + fDay; // adjust to count today as a counted dayevent.value = Math.floor(diff/ fYear); // truncate to whole years}
gkaiseril
Expert
Registered: Feb 23 2006
Posts: 4307
No, you will need to change the 'DOB' field name to 'PATIENTS_AGE', your field name. There is also an expected field called 'Today' that is picking up the value of the field called 'Today'.

You will also have to change the the date formats from 'mmm d, yyyy' to 'mm/dd/yyyy' to get the correct conversions.

George Kaiser

rrwester
Registered: Oct 8 2009
Posts: 7
I know I'm getting close!
I added a text field named "Today" and copied the calculation script from another post. It did put today's date automatically. YEAH!! (and thank you Try67 for the posted answer!)

I changed the "PatientsAge" field to the following calculation:
// define some time constants
var fSec = 1000; //second
var fMin = 60 * fSec; // minute
var fHr = 60 * fMin; // hour
var fDay = 24 * fHr; // day
var fYear = 365.25 * fDay; // year

var strStart = this.getField("PatientsAge").value; // PatientsAge
// var strToday = util.printd("mm/dd/yyyy", new Date()); // get system date time
var strToday = this.getField("Today").value;
// compute if there are values for DOB and Today
if(strStart.length & strToday.length) {
var DOB = util.scand("mm/dd/yyyy", strStart); // convert DOB to date time object
var Today = util.scand("mm/dd/yyyy", strToday); // convert today to date time object
var diff = Today.valueOf() - DOB.valueOf(); // compute difference of values
diff = diff + fDay; // adjust to count today as a counted day
event.value = Math.floor(diff/ fYear); // truncate to whole years
}

However, the "PatientsAge" field is still empty though the "Today" and "DOB" fields have mm/dd/yyyy answers in them. (Today/Calculated and DOB entered manually)

So, 2 questions:
1) What have a messed up in this form that would not cause a Syntax error, but will not allow the calculated answer to PatientsAge to display?
2) Is there a good resource or forum that explains the code symbols utilized in the Java Script? (ie: what the //'s stand for - I am thinking it just represents what the prior code is set to do; but why the semicolons, etc? Any good resource for beginners would be groovy!
Dimitri
Expert
Registered: Nov 1 2005
Posts: 1389
Hi rrwester,

// is a symbol for denoting Comments by the code developer. Any text between // and the end of a line is ignored by JavaScript.

A best book on Core JavaScript (that also contains a list of most of the symbols used in the index) is Dave Flanagans "JavaScript The Defintive Guide" by O'Reilly.

You should also get the proper Acrobat JavaScript documentation from the Adobe web site if you want to understand what you are doing rather than just copying and pasting code. If you just want to copy/paste that's fine but read the Blog entry below for some of the issues surrounding using other people's code-
http://www.acrobatusers.com/blogs/thomp/copying-and-pasting-code

Hope this helps,

Dimitri
WindJack Solutions
www.windjack.com
www.pdfscripting.com
rrwester
Registered: Oct 8 2009
Posts: 7
I have learned in copying and pasting codes provided, to modify the field names to match those of my form, and ensure none are duplicated elsewhere in the form itself. I could not even begin to tell you how many I have successfully modified and used; and my deep appreciation to those on this forum that have been kind enough to post.

At any rate, I will definitely investigate the book you suggested.

Therefore question 2 is answered. Meanwhile I will continue trial and error and hope to post MY OWN answer for question 1 (That'd be a nice self-accomplishment anyway, ha!).
Dimitri
Expert
Registered: Nov 1 2005
Posts: 1389
Hi rrwester,

Is your field named "Patient_Age" or "PatientsAge" ? Please do read the blog entry ( link in my previous post) on copy/pasting code for some valuable tips.

Hope this helps,

Dimitri
WindJack Solutions
www.windjack.com
www.pdfscripting.com
rrwester
Registered: Oct 8 2009
Posts: 7
Oh believe me, I have :-)
I go so far as to print and highlight codes to find the fields I need to change the name to. I know that is a big issue when copy/pasting other calculations.

As far as the Patients_Age, vs PatientsAge...I changed it to have no underscore, after reading another blog that suggested NOT using underscores or spaces and to just use small/cap letters. I should have mentioned that to prevent cluttering this blog with another post. Sorry!

UPDATE: I GOT IT!!! THANK YOU DEAR LORD FOR YELLOW HIGHLIGHTERS AND LOTS OF PATIENCE....OH YES, AND GKAISERIL. Yes, I am doing a happy dance at the moment!!
Dimitri
Expert
Registered: Nov 1 2005
Posts: 1389
Hi rrwester,

I had a bit of time so I tested out the code from gkaiseril in this thread and it all works for me- except that I do not have the date field code for Today that you got from try67 ( I entered my own). Maybe check that code to make sure the date format matches what the calc field expects.

Hope this helps,

Dimitri
WindJack Solutions
www.windjack.com
www.pdfscripting.com
jean299
Registered: Nov 15 2009
Posts: 19
I need an age in months and years. On my LiveCycyle form I have two date fields 'dob' and 'rdtestdate'.
I am in Australia so we use dd/mm/yyyy as the format.
The field designated to display the calculated result -- 'ageyrsmnths' -- is set as a calculated-read only text field.

What javascript code would I use to calculate the age in years and months, please? I've been studying and testing the various solutions but don't understand well enough, sorry!
thomp
Expert
Registered: Feb 15 2006
Posts: 4411
Take a look at this series of Articles:
http://acrobatusers.com/tutorials/2006/date_time_part1

The sample forms should help you out.


Thom Parker
The source for PDF Scripting Info
www.pdfscripting.com
Very Important - How to Debug Your Script

jean299
Registered: Nov 15 2009
Posts: 19
Thanks very much. I don't see anything in those tutorials that enable the result in the form that I need, that is years and months.

I have got a simple formcalc script working to get an age (given two date fields) in years, with a decimal showing part of a year. But what we need is the result to show the person's age in years and months rather than years with decimals.

The formcalc script I am using is (NB: format is for Australia and 7 & 52 provide the best approximation for me):
_____
if (HasValue(dob)) then
if (HasValue(rdtestdate)) then
var rdtestdate_ = Date2Num(rdtestdate.formattedValue, "DD/MM/YYYY")
var dob_ = Date2Num(dob.formattedValue, "DD/MM/YYYY")
var diff = rdtestdate_ - dob_
$.rawValue = Round((diff /7)/(52),2)
else
$.rawValue = null
endif
else
$.rawValue = null
endif
_____
If anyone can assist with changing the result to years and months rather than years with decimals, I would be most grateful.
Many thanks,
jeannie
thomp
Expert
Registered: Feb 15 2006
Posts: 4411
Well, there are 12 months in a year, so if the decimal portion of the year number is multiplied by 12 you'll get the number of months. It's just a matter of separating out the decimal portion.

Given your current calculation this should work:

var nYears = Floor($.rawValue)
var nMonths = Round($.rawValue - nYears) * 12);

If you want something more exact, since not all months have the same number of days you'll need to perform the calculation differently. perform the number of years calculation by subtracting the years for the two dates, then find the difference between the months in the two dates. If the difference is negative, i.e. current month is less than the birthday month, then subtract a year and add 12 to the month difference.

Thom Parker
The source for PDF Scripting Info
www.pdfscripting.com
Very Important - How to Debug Your Script

jean299
Registered: Nov 15 2009
Posts: 19
Thanks Thom,

So, I need two text fields for the result, one for years and the other for months, is that correct?

The code for the years field would be as I have it above, but change Round to Floor and remove the decimals.

And the code for the new months field would be:
________________
if (HasValue(Page1.studentdetails.dob)) then
if (HasValue(rdtestdate)) then
var rdtestdate_ = Date2Num(rdtestdate.formattedValue, "DD/MM/YYYY")
var dob_ = Date2Num(Page1.studentdetails.dob.formattedValue, "DD/MM/YYYY")
var diff = rdtestdate_ - dob_
var nyears = Floor((diff/7)/(52))
$.rawValue = Floor((((diff/7)/52) - nyears)*12)
else
$.rawValue = null
endif
else
$.rawValue = null
endif
________________

This seems to work fine. Thanks for your assistance.

One additional question, is it possible to add some text in the field after the calculation so that, for example, the years would be reported as “9y” rather than just “9” — and the months like “3m” instead of just “3” — I don’t suppose you have a little tweak for that???
Tomme
Registered: Jun 2 2011
Posts: 11
I have read post after post after post and can still not get an AGE to calculate when a date is placed in a field. I am EXTREMELY new to this and feel defeated already.
I need the age to go into a field titled "AGE" that is calculated from a date of birth field titled "DOB"
I have the current date being automatically filled in when the PDF opens in a field titled "DOS3"

I need some help! I am just a fireman, this is FAR above my pay grade! I am using Adobe Professional 9 (I think).



thomp
Expert
Registered: Feb 15 2006
Posts: 4411
First, What kind of form do you have. Was it created in LiveCycle or Acrobat?

Take a look at this article:
http://acrobatusers.com/tutorials/2006/date_time_part1

There's an example for part 2 that shows a difference calculation, you should be able to copy it into your form.

Thom Parker
The source for PDF Scripting Info
www.pdfscripting.com
Very Important - How to Debug Your Script

jean299
Registered: Nov 15 2009
Posts: 19
Greetings,

I struggled with this some time ago and got it working with a very simple fix. Here is the blog entry I put up at work so that others can follow:

To calculate a chronological age in years and months given two date fields requires the creation of a calculated field with a script that works out the problem for you. There are a lot of complex scripts available for working with dates. Depending on how precise your information needs to be, you may want to seek out the script that best suits your needs. This example provides a very simple script that is precise enough for working out the chronological ages of children in a school program given their birthdate and another date, e.g. the date of a reading test.

Assuming you have already created two date fields to be used as references in your calculations, the first thing to do is to create two text fields (for years and months) and make them both Calculated - Read Only using the Value tab.

Take note of where the new fields are located in the Hierarchy, because if they are in a different subform or on a different page from the date fields being referenced, you have to use the full paths in the formula instead of just the field names, which are used in the example below.

Second, select each field in turn and paste in the following scripts for the fields.

How to paste in a script:

1. Use the Window menu and select Script Editor to open the area where scripts can be typed or pasted.

2. Select Calculate from the dropdown menu labelled 'Show' to open the specific section where calculation scripts are entered.

3. From the 'Language' dropdown menu select FormCalc, because the script being used here is in that language.


NB: (I have red and green text in my blog entry to indicate form field names and text strings used as names for variables in the formulae, but this post can only have black text. Whish I could attach the rich text file so you can see that. Here is the link for that blog entry, but it may only be available to people in my workplace https://www.det.nsw.edu.au/blog/157646-computerhowtos/entry/calculate_age_from_two_dates)

The text in red below shows the form field names. (These are also encased in parentheses.) You need to substitute these with your own form field names for your date fields. (The oldest date goes where the dob field is referenced, and the most recent date goes where the testdate field is referenced. Also, if the fields are not in the same subform or on the same page, you have to put in the full path, e.g., instead of simply dob (for date of birth) you might put Page1.studentdetails.dob.


The text in green below is whatever short text string you want to label the variables used in the calculation. (These are also prefaced with the term 'var') An example of labelling variables used in the scripts below is -- The part of the script that converts the date of birth into a computer generated number representing a number of days is called dob_. For simplicity, the field name with an underscore was used to label this variable, but any other text string could have been used, like dobindays.


Here is the FormCalc code used:


for the year field


---------------------------------------------





if (HasValue(dob)) then
if (HasValue(testdate)) then
var testdate_ = Date2Num(testdate.formattedValue, "DD/MM/YYYY")
var dob_ = Date2Num(dob.formattedValue, "DD/MM/YYYY")
var diff = testdate_ - dob_
$.rawValue = Floor((diff /7)/(52))
else
$.rawValue = null
endif
else
$.rawValue = null
endif





---------------------------------------------





for the month field



---------------------------------------------





if (HasValue(dob)) then
if (HasValue(testdate)) then
var testdate_ = Date2Num(testdate.formattedValue, "DD/MM/YYYY")
var dob_ = Date2Num(dob.formattedValue, "DD/MM/YYYY")
var diff = testdate_ - dob_
var nyears = Floor((diff/7)/(52))
$.rawValue = Floor((((diff/7)/52) - nyears)*12)
else
$.rawValue = null
endif
else
$.rawValue = null
endif





----------------------------------------------



Goodluck with your date calculations!



jean299
Registered: Nov 15 2009
Posts: 19
p.s. I am talking about using LiveCycle Designer ES 8.2