Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Calculate the age of someone

Go to End

4 Posts   1329 Views


Community Member, 11 Posts

27 May 2016 at 2:25am

Hi everyone,

i been trying a lot lot of things, searched everywhere but got confused between Date field, SS_Datetime and the diff diffIn functions, i basically didn't achieve a single calculation between a $DateOfBirth field written in the db and either Date() or SS_Datetime::now

Is there any concrete code example where i can see how to find the age of someone based on his/her birthday ?


Community Member, 17 Posts

27 May 2016 at 11:22pm

Edited: 27/05/2016 11:44pm

(full working code for silver 3.x if anyone else need)

Asume u have page called PersonPage


class PersonPage extends Page {

private static $db = array(
'DateOfBirth' => 'Date'

public function getCMSFields() {
        $fields = parent::getCMSFields();
	$fields->addFieldToTab("Root.Main", new DateField('DateOfBirth'));
        return $fields;

class PersonPage_Controller extends Page_Controller {

public function Age() { 
$birthdate = $this->DateOfBirth; // person birth date
$datetime = date('Y-m-d'); // date doday
$year = date_diff(date_create($birthdate), date_create($datetime))->y; // calculation and formating to year
return $year;

In template

<div>Person age: $Age </div>

Let me know if any problems, should work correct.


Community Member, 17 Posts

27 May 2016 at 11:28pm

Edited: 27/05/2016 11:31pm

u can also write same function a bit nicer:

public function Age() { 
$birthdate = new DateTime($this->DateOfBirth);
$datetime = new DateTime(date('Y-m-d'));
$year = $birthdate->diff($datetime)->y;
return $year;


Community Member, 11 Posts

28 May 2016 at 2:01am

Edited: 28/05/2016 2:01am

Hi, Friizu

It works perfectly, thanks for the support. I will use the code in the website Thanks again