# Calculate Age

how can i calculate age from birthday ( birthday is stored on my dataabse) and view on my cgridview view?

Hi

check this example

``````
\$datetime1 = new DateTime('the birthday date from database');

\$datetime2 = new DateTime();

\$diff = \$datetime1->diff(\$datetime2);

\$diff->y //years

\$diff->m //months

\$diff->d //days

``````

but there is more correct way directly from database. If you want it please inform us

You can use This Post to calculate difference.

In cgrid view pass current date to a function which return calculated result.

``````

// This code in gridview for column

array(

'name'=>'bdate',

'filter'=>'',

'value'=>'getBdateCalculation(\$data->bdate)',

),

//Function that calculate result

function getBdateCalculation(\$bdate)

{

//Calculation here

return \$result;

}

``````

Kiran gave us the left part of the solution!

just add in getBdateCalculation like that

``````
function getBdateCalculation(\$bdate)

{

\$datetime1 = new DateTime(\$bdate);

\$datetime2 = new DateTime();

\$diff = \$datetime1->diff(\$datetime2);

return \$diff->y;

}

``````

thank you for help guys…

but the result is not correct this is my code:

on my model

function getBdayCalculation(\$bday)

{

\$datetime1 = new DateTime(\$bday);

\$datetime2 = new DateTime();

\$diff = \$datetime1->diff(\$datetime2);

return \$diff->y;

}

on my Cgridview:

array(

‘name’=>‘bday’,

‘filter’=>\$model,

‘value’=> CHtml::encode(\$model->getBdayCalculation(\$model->bday)),

),

i got result of 0.

1. put the method getBdayCalculation to the controller

2. replace

``````
'value'=> CHtml::encode(\$model->getBdayCalculation(\$model->bday)),

``````

with

``````
'value'=> CHtml::encode(\$this->getBdayCalculation(\$data->bday)),

``````

Also check if the values are corrected using var_dump

Make sure your \$bday is in ‘Y-m-d’, and KonApaz’s update is correct.

Undefined variable: data

this is my code on cgridview

this view is on my admin cgridview

‘value’=> CHtml::encode(\$this->getBdayCalculation(\$data->bday)),

try this

``````
'value' => 'CHtml::encode(\$this->getBdayCalculation(\$data["bday"]))',

``````

PROBLEM SOLVE

sorry its all my bad the code on my cgridview is wrong thank you all for the help specially to konapz…

my code on cgridview admin page: ‘value’=>’\$data->getBdayCalculation(\$data->bday)’,