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.

Comments

Witch’s picture

does anybody know why the computed field always displays the number "9" no matter which date i choose?

Here is what the date field bday stores in database "2006-05-17 00:00:00"

this is my computed field

Computed Code:

$birthday_date = date_make_date($node->field_bday[0]['value']);
$birthday = $birthday_date->db->parts;

//compute age
$bdayunix = mktime(0, 0, 0, $birthday['mday'], $birthday['mon'], $birthday['year']);
$nowunix = time();
$unixage = $nowunix - $bdayunix;
$age = floor($unixage/ (365 * 24 * 60 * 60));

$node_field[0]['value'] = $age;

Display Format:
$display = $node_field_item['value'];

doomed’s picture

Weird, i'm getting the same "9" value.

After a while, just a "0" (zero).

Also this error message comes up after editing / submiting a node:


Parse error: syntax error, unexpected '<' in C:\apache\htdocs\drupalxxx\sites\all\modules\computed_field\computed_field.module(138) : eval()'d code on line 1

What gives?

doomed’s picture

finke77’s picture

Hello!

Try this one (field_profile_birthday is the "birthday field):

$isoArray = explode ( '-', substr($node->field_profile_birthday[0]['value'],0,10));
$bdayunix = mktime ( 00, 00, 00, (int)$isoArray[1], (int)$isoArray[2], (int)$isoArray[0]);

//compute age
$nowunix = time();
$unixage = $nowunix - $bdayunix;
$age = floor($unixage/ (365 * 24 * 60 * 60));

$node_field[0]['value'] = $age;

explode generates an array with year / month / day. mktime generates the unix timestamp.

Best regards,

Christian

tommytom’s picture

I always get the number 9 as age.

I in the profile options I created a field profile_birthday and in computed field I copy your code.

Why it's not working ? I'm on drupal 6.10

tommytom’s picture

I put this code in computed field and it's working:

global $user;
profile_load_profile($user);

$year_diff = date("Y") -  ( $user->profile_dob['year']);
$month_diff = date("m") - ($user->profile_dob['month']);
$day_diff = date("d") - ($user->profile_dob['day']);
if ($month_diff < 0)
  $year_diff--;
elseif ($month_diff == 0 && $day_diff < 0)
  $year_diff--;


$node_field[0]['value'] = $year_diff ;
realityloop’s picture

if (!$node->nid) node_save($node);
$age = ((time() - strtotime($node->field_dob[0]['value'])) / (3600 * 24 * 365));
$node_field[0]['value'] = ((int) $age) ;
if (is_null($node->field_dob[0]['value'])) $node_field[0]['value'] = NULL ;
stevebab’s picture

Thanks realityloop.

That works in computed field like a CHARM -- with one tiny change:

A few days drop off because of the value placed for a year -- "365"

So I just added the approximate decimal value to add a day every four years -- "365.25" -- and it seems to work great.

It still might stumble with leap centuries, but should suffice for most age calculations.

Finally, I was able to just use the middle two lines of code with a nice, clean result.

$age = ((time() - strtotime($node->field_eval_dob[0]['value'])) / (3600 * 24 * 365.25));
$node_field[0]['value'] = ((int) $age) ;
iparsin’s picture

Thank you for the code. Anyway, how to prevent "0" to display or at least echo some string like "less than one year".

Thanks in advance,
iparsin

jaochoo’s picture

It is said here that "you'll need to check the 'Store using the database settings below' checkbox". Now if I store the computed value in the database rather than letting it compute everytime, won't the age be the same age all the time as it is written as a static value to the database? E.g. subtracting my date of birth from today would result in 26 years which is written to the database. Next year, however, the computed result would be 27, yet still using the value 26 from the database.

On the other hand, not writing it to the database but letting it compute on-the-fly would result in an always up-to-date age (which probably is what we want to achieve), but it would would be impossible to use it with Views (which probably is what we want to do, in particular with user profiles as the most prominent area where to display an age value).

ludo1960’s picture

Can't you use the http://drupal.org/project/views_customfield module ? If someone knows how please post back here.

trevorjfitz’s picture

ludo1960, thanks for the idea. I tried it out and sure enough I got it to work. The module is straight forward, it basically just adds 3 special fields to choose from in Views.

This was my problem: In the content, there was a year that attorneys had started practicing. I wanted to easily calculate the number of years practicing - a bit simpler than calculating birthdays, but same idea.

First, I added the field that had the year in it: field_start_year. I excluded this field from display.

Then, I added the custom php field (thanks to your module suggestion) and typed this as the code:

<?php echo (date("Y") - ($data->node_data_field_portrait_field_start_year_int_value)); ?>

Hmm, now that I look at the code I just pasted in, I'm not sure where the "field_portrait" came from, although that is the name of another field of mine. Strange, but it doesn't seem to mess up the functionality. To figure out what to put after the "data->" type in the php code box:

<?php print_r($data); ?>

That will show you everything available to use in the field.

Good luck!

ptoly’s picture

Using http://drupal.org/project/views_customfield

I added this php snippet to parse the serialized data into an age:

<?php
// get the profile dob value into an array
 $bday_array = unserialize($data->profile_values_profile_birthday_value);

//compute age
 $bdayunix = mktime(0, 0, 0, $bday_array['month'], $bday_array['day'], $bday_array['year']);
 $nowunix = time();
 $unixage = $nowunix - $bdayunix;
 $age = floor($unixage/ (365 * 24 * 60 * 60));

 print $age;
 ?>
johnhesston’s picture

This was by far the easiest way of doing it..!

Berliner-dupe’s picture

// get the profile dob value into an array
$bday_array = unserialize($data->profile_values_profile_birthday_value);

//compute age
$bdayunix = mktime(0, 0, 0, $bday_array['month'], $bday_array['day'], $bday_array['year']);
$nowunix = time();
$unixage = $nowunix - $bdayunix;
$age = floor($unixage/ (365 * 24 * 60 * 60));

print $age;

This dont work for me. I get ever "10"!!!!! We have 2010 - i think there is an error in Code then the "10" is comming from 20(10)!

Has anyone an idea?

mojito_’s picture

I'm getting '11' so think you must be right in thinking this comes from the year. Did you find what was wrong?
Thanks

Berliner-dupe’s picture

Hi,

i use this Code in a "Views-Customfield" for calculating age from a "Date-Field-birthday". It works great ...

Please change it to your requirement.

if ($data->node_data_field_1_geburtstag_field_1_geburtstag_value != NULL) {
$output ="";
$gebdat = $data->node_data_field_1_geburtstag_field_1_geburtstag_value;
$gebjahr = date(Y,$gebdat);
$gebmon = date(n,$gebdat);
$gebtag = date(j,$gebdat);

$year_diff = date("Y") - $gebjahr;
$month_diff = date("m") - $gebmon;
$day_diff = date("d") - $gebtag;
if ($month_diff < 0)
  $year_diff--;
elseif ($month_diff == 0 && $day_diff < 0)
  $year_diff--;

$output.=$year_diff." Jahre ";
print $output;
}
mojito_’s picture

Thanks!

kansertjr’s picture

I created a new CCK which there Multigroup containing job history. Multigroup will save someone employment history
I want to show how long someone works from last data on the Multigroup

entendu’s picture

Easiest way to calculate age based on a timestamped birthday:

$years_passed = date('Y') - date('Y', strtotime($your_timestamp));
if(date('md') < date('md', strtotime($your_timestamp))) {
$years_passed--;
}
return $years_passed;

Hackish, but date('md') will generate a four-digit number like 0914 (Sept. 14th) which will be less than, say, 0522 (May 22nd).

filiptc’s picture

In case you were working on a CCK date field. Make sure you replace the actual field name.

//compute age
$bdayunix = strtotime($data->node_data_field_role_field_birthdate_value);
$nowunix = time();
$unixage = $nowunix - $bdayunix;
$age = floor($unixage/ (365 * 24 * 60 * 60));

print $age;
pauljr8’s picture

I was wondering if you could help me more than you have. Using your //compute age script would this work and where/how would I employ it? $age will be used to determine which form to present next.
$form['renter']['birthday'] = array(
'#type' => 'date_select',
'#title' => 'Date of Birth',
'#date_format' => 'm-d-Y',
'#default_value'=>'',
'#date_label_position' => 'within',
'#date_year_range' => '-100:+0',
);
//compute age
$bdayunix = strtotime($form_state['values']['birthday']);
$nowunix = time();
$unixage = $nowunix - $bdayunix;
$age = floor($unixage/ (365 * 24 * 60 * 60));

print $age;

Thanks

filiptc’s picture

Sorry, I didn't see your response until now. Did you figure it out? I guess if $form_state['values']['birthday'] holds a datestring that is recognizable to php it should work.

chinita7’s picture

Is it possible to achieve this with profile date field but not with cck date field ?

spineless’s picture

Hello,

This is how I created an "Age" field for Drupal 7.

I am using the following modules:

date
computed field

In the computed field I have the following code:

<?

$entity_field[0]['value'] = ((time() - strtotime($entity->field_birthday[LANGUAGE_NONE][0]['value'])) / (3600 * 24 * 365.25));
?>

Display code (php);
<?
$display_output = $entity_field_item['value'];
?>

harings_rob’s picture

And how do you update these?

llorberb’s picture

Thanks.

I added age groupings so that a range would be shown instead or a number.

Computed Code:

$age = ((time() - strtotime($entity->field_profile_dob[LANGUAGE_NONE][0]['value'])) / (3600 * 24 * 365.25));

if ($age <= 18) {
$entity_field[0]['value']  = "< 18";
} elseif ($age <= 24) {
$entity_field[0]['value'] = "19 to 24";
} elseif ($age <= 35) { 
$entity_field[0]['value'] = "25 to 35";
} elseif ($age <= 50) {
$entity_field[0]['value'] = "36 to 50";
} else {
$entity_field[0]['value'] = "> 50";
}

display code:

$display_output = $entity_field_item['value'];
ghmercado’s picture

brilliant thank you so much

drvdt’s picture

Thank spineless,
It works
Note for newbie:
- Change field_birthday to your field

My sites: Medicare