Calculating Age from Date of Birth

Usually we store users dates of birth in our database table, in a DATE field type. You can easily calculate the age of your users, using the App Connect Data Formatter component on your page.

We created a dynamic table, displaying the data from our database and one of the columns displays the dates of birth. It’s currently displaying the dates in the default database format, but you can format them as you need (that’s not the topic of this tutorial) :

The first thing we need to do is to add the Date and Time Component on the page. It’s a variable which returns the current date. Select App and add new component:

Open Data and select Date and Time:

Open the interval dropdown:

And set the interval to days, as we don’t need to count the hours/minutes/seconds in this case:

Then select your dynamic table and click the Run button, to open the dynamic table generator dialog:

Add a new column:

We enter Age for the column header (1), and then change the cell type to custom (2). Click the Ok button:

You can see that our Age column is now added to the table:

Select the first cell in the Age column and click the dynamic data picker for its text property:

Select the date of birth column from your database and click the data formatter button:

Right click the date of birth binding, open the Date and Time menu and select Years Until:

Then click Date and then click the dynamic data picker button, in order to select a date to compare (calculate years to):

We want to compare the database date, with the current date/year - so select the datetime property under the Date and Time component:

Click Select in order to apply the selection:

Click Select to add the selected value to the table cell:

And you are done. You can see your users’ age in the Age column:

3 Likes

Hi, I think there is a problem with the example, if we calculate only the years between the two dates, it will not give the correct age since if the person was born on 2020-12-01 and the current date is 2020-09 -30 he or she is not 20 but 19.

1 Like

How do I get sorting to work on a calculated field like this?
I’m trying to do something similar, but sorting doesn’t work because it’s expecting the values to be in the table. Can I do a calculated field on the server? I think I can with a custom query, but that seems like kind of a lot of work to go to for just one field.
Thoughts?

{{date_of_birth.yearsUntil(var1.datetime.formatDate(‘yyyy-MM-dd’))}}

1 Like

You are correct. This is not a valid approach to computing age in years.

1 Like

I use something like this:

(queryname.dateOfBirth.dateDiff('months', NOW) / 12).floor()

Ylou can also use ceil() if you want to round upwards

1 Like