-date
-selector
-no timezone
-no multiple option
-required, Yes

I want to calculate a person's age based on the birthday and print it in their nodeprofile. Please give me guidance on how to code such a process.

Thank you,
mullet

Comments

lias’s picture

try this, substitute field_birthdate with your birth day field name.

<?php
        $birthdate = $node->field_birthdate[0]['value'];
        $now = time();
        $then = strtotime($birthdate);
        $diff = date('Y', $now) - date('Y', $then);
        print $diff;
        ?> 
droople’s picture

where does that code go?

lias’s picture

in your node_profile.tpl.php template

macgirvin’s picture

It's not quite that easy (the calculation). You have the same age as last year up until your birthday, at which point you become a year older. So using the above example we can make it work a bit better by subtracting a year if the birthday hasn't yet rolled around this year. The 'z' modifier to date() gives you the numerical day of the year (0-365). There are many better ways to accomplish this that are likewise outside the scope of the current issues list.

<?php
        $birthdate = $node->field_birthdate[0]['value'];
        $now = time();
        $then = strtotime($birthdate);

        $diff = date('Y', $now) - date('Y', $then);

        if($diff < 0)      /* ideally you want to prevent this from happening */
           echo '??? - negative age.';

        if(($diff > 0) && (date('z',$now) < date('z',$then)))
           $diff --;
 
        print $diff;
        ?>
Passionate_Lass’s picture

Is it possible to do this within a view, and permit it to be filtered?

karens’s picture

Status: Active » Fixed

I'm not making changes to the 5.1 version. I'm officially recommending you move to the 5.2 version now. If you have problems in that version you can check for existing issues or add new ones. Feature requests are now getting posted to the D6 version to be back-ported to 5.2.

I believe there is a feature request or support request about working with ages already posted somewhere.

Anonymous’s picture

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for two weeks with no activity.