Calculating age from birthday
Last updated on
30 April 2025
PLEASE NOTE These snippets are user submitted. Use at your own risk.
Timur Gilfanov uses the following code in a computed field to find the current age of someone given their birthdate:
$birthday_date = date_make_date($node->field__[0]['value']);
$birthday = $birthday_date->db->parts;
//compute age
$bdayunix = mktime(0, 0, 0, $birthday['mon'], $birthday['mday'], $birthday['year']);
$nowunix = time();
$unixage = $nowunix - $bdayunix;
$age = floor($unixage/ (365 * 24 * 60 * 60));
$node_field[0]['value'] = $age;
Another method, this one using the timezone information of the Drupal system. This ensures that someone in Japan sees the age correctly if it happens to be the day of the birthday while in America they should still see the old age.
// $age = Current Year - Birthday Year - bool(Birthday hasn't arrived yet)
$age = format_date(time(),'custom','Y') - $birthday['year'] - (format_date(time(),'custom', 'nd') < $birthday['month'] . str_pad($birthday['day'],2,0,STR_PAD_LEFT));
For either of these snippets you'll need to check the "Store using the database settings below" checkbox on the field's configuration page to use the database values.
Help improve this page
Page status: Not set
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion