Calculate age from date in MODX

Sometimes we may need to display an age in years, passed from some date. For example, it can be a simple self-introducing line like "I am X years old" on a personal web page. Of course, it is not the best idea to update it manually each year. Fortunately, we should not.

In this article we will write a snippet which will calculate the age based on any initial date. All we need is just call it like here:

 I am [[Age? &year=`1990`]] years old

And, if today was 2012, it would output:

I am 22 years old

If we need it to be more exact and display the age in full years depending also on month and even day, we can do it too:

I am [[Age? &year=`1990` &month=`9`]] years old
I am [[Age? &year=`1990` &month=`9` &day=`5`]] years old

Below is the full snippet code. It is pretty simple and equal for both REVO and EVO.

$year  = isset($year)  ? (int) $year  : 0;
$month = isset($month) ? (int) $month : 0;
$day   = isset($day)   ? (int) $day   : 0;

$age = date('Y') - $year;

if (intval($month . str_pad($day, 2, '0', STR_PAD_LEFT)) > date('nd'))

return $age;

Let's quickly review it. First, we're collecting the parameters which may be passed to the snippet — year, month and day. Right after that snippet calculates the difference between today's and initial years, without worrying about the month and day.

The last piece of code compares today's date with initial one and, if the birth day has been not reached yet, decreases age by one. For this purpose both dates are represented in "MDD" format (month of year and day of month with leading zero). For example, let's imagine birth date is September 15th, and today's date is June 5th. In described format, they becomes as 915 and 605, and as far as first one is greater than second one, the age will be decreased.

By on
If you want to repost this article, please keep the source hyperlink