[support] Average age from date of birth

Maarten van Grootel mvgrootel at gmail.com
Wed Oct 8 22:50:17 UTC 2008


Calculate the current age of all users. Then sum and divide by the total
amount of users. For a less accurate solution you could suffice by
calculating the age just by averaging over all the years of birth, and
subtracting 0.25. We assume then that birthdays are spread out uniformly,
and thus subtraction of 0.25 is necessary to compensate for the birthdays in
Oct, Nov, and Dec that still haven't passed yet.

Problem is that the Profile module saves its date field as a serialized
array, so you have to do all the work in PHP in stead of directly on the
database.

Because I use the Birthdays module (which stores its birthdays as datetime
values), I can directly calculate it from the database using the below
methods.
// Short, inaccurate method
avg(year(now() - year(birthday)) - 0.25 = 24,2 years old

// Longer, but more accurate method.
avg((year(now()) - year(birthday))+(DAYOFYEAR(now()) > DAYOFYEAR(birthday)))
= 24.2 years old

In PHP you want something like this:
<?php
$result = db_query("SELECT value FROM {profile_values} WHERE fid = %d",
$profile_field_id_of_date_field);
$i = 0;
$sum = 0;
while ($row = db_fetch_object($result)) {
  $dob = unserialize($row->value);
  if(is_array($dob)) {
    extract($dob);
  }

  if ($day && $month && $year) {
    // Current year - birthday_year - (1 if birthday hasn't been yet)
    $age = (date('Y') - $year) - (date('nd') < $month . str_pad($day, 2, 0,
STR_PAD_LEFT));
    $sum += $age;
    $i++;
  }
}
$average_age = $sum / $i;
?>

On Wed, Oct 8, 2008 at 3:48 PM, Rohan Smith <rohanasmith at gmail.com> wrote:

> how could i calculate average age of my members using a profile
> date_of_birth date field?
>
> --
> [ Drupal support list | http://lists.drupal.org/ ]
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.drupal.org/pipermail/support/attachments/20081009/50062b11/attachment-0001.htm 


More information about the support mailing list