Javascript code to calculate age from a Date Of Birth field

Post any questions you have about using the Verj.io Studio, including client and server-side programming with Javascript or FPL, and integration with databases, web services etc.

Moderators: Jon, Steve, Ian, Dave

Hovik
Moderator
Moderator
Posts: 184
Joined: Tue Sep 11, 2007 8:58 am

Javascript code to calculate age from a Date Of Birth field

#1

Postby Hovik » Tue Apr 23, 2013 4:24 pm

Code: Select all

var dateNow = new Date();
var dateDOB = new Date(fields.DOB.value);

var yearNow = dateNow.getFullYear(); //getting current year
var mnthNow = dateNow.getMonth();
var dayNow = dateNow.getDate();

var yearDOB = dateDOB.getFullYear(); //getting dob year
var mnthDOB = dateDOB.getMonth();
var dayDOB = dateDOB.getDate();

//calculating age
if ( (mnthNow > mnthDOB) || (mnthNow==mnthDOB && dayNow >= dayDOB) )
   {fields.AGE.value = yearNow - yearDOB;}
else
   {fields.AGE.value = yearNow - yearDOB - 1;}
0 x

AJDulk
Ebase User
Posts: 94
Joined: Fri Sep 14, 2007 12:18 pm
Location: The Netherlands
Contact:

Some considerations when using Dates in JavaScript

#2

Postby AJDulk » Mon Aug 19, 2013 12:03 pm

If you want to check if a Date field is populated or not then use the following:

Code: Select all

if (fields.DATE_FIELD_NAME.displayValue) { ... }
instead of:

Code: Select all

if (fields.DATE_FIELD_NAME.value) { ... }
There is a problem when using value and someone fills in the 1st of January 1970, value gives a 0 back and therefore JavaScript sees it as being empty (false instead of true since 0 and null is false and anything else is true).

--

For some reason using

Code: Select all

new Date.getFullYear()
throws an error, instead use

Code: Select all

new Date().getFullYear()
to get the current year without having to create any extra variables.

To get the current date you can also use

Code: Select all

Date.now()
which is a little easier than doing

Code: Select all

system.variables.$SYSTEM_DATE.value
Last edited by AJDulk on Wed Sep 25, 2013 11:42 am, edited 1 time in total.
0 x

AJDulk
Ebase User
Posts: 94
Joined: Fri Sep 14, 2007 12:18 pm
Location: The Netherlands
Contact:

Function: getNumberOfDays(dateInMilliseconds)

#3

Postby AJDulk » Tue Sep 10, 2013 10:29 am

To convert to number of days use:

Code: Select all

function getNumberOfDays(dateInMilliseconds) {
	return Math.floor(dateInMilliseconds / 84600000);
}
Note that JavaScript in Ebase automatically gives a date in milliseconds.
Example of use:

Code: Select all

if (getNumberOfDays(fields.END_DATE.value - fields.START_DATE.value) > 14) {
  event.owner.addErrorMessage("Maximum number of days exceeded!!!");
}
0 x


Who is online

Users browsing this forum: No registered users and 19 guests