Age Calculation

I store the user’s date of birth in my database table, and I have a function in my User model which calculates the user’s age. This is all good and well when retrieving the user’s age, but what about when I want to query the database for users of a specific age, or users between two specific ages?

What is the correct method of doing this? How do I code this in CDbCriteria?

I would probably store the age as a separate field and have it updated somehow (script running on crontab or similar). That way you could easily do such queries.

Best way for that is eg.user is 11-12-1987 like me :) and the second one is 11-12-1988

AGE is name of your date of birth column

$user = User::model()->findAll(array(



'condition'=>'WHERE AGE BETWEEN \'1987-12-11\' AND \'1988-12-11\' '



I don’t think this is the best but this should working

the age between 5 to 10 for example



$criteria=new CDbCriteria();

$criteria->condition='dateOfBirth between :minAge and :maxAge';

$criteria->params=array(':minAge'=>date('Y-m-d', mktime(0, 0, 0, date("m") , date("d"), date("Y") - $minAge)), ':maxAge'=>date('Y-m-d', mktime(0, 0, 0, date("m") , date("d"), date("Y") - $maxAge)));


i think best way for me :)

To store the age is not a great idea, you have just to manke 2 calculation in php.

For example you can use strtotime for create the dates for search:


      ':minAge'=> date('Y-m-d',strtotime("- {$this->min_age} years"), 

       ':maxAge'=> date('Y-m-d',strtotime("- {$this->max_age} years"));

<?php echo)?>

This funcion will work correctly even with month or days intervals

$criteria->condition = 'timestampdiff( year, birthday, curdate( ) ) > 33'

timestampdiff is mysql only