I want to calculate a voters age base on her birthday, in my entity, I created a function like this
//voters.php
public function getAge()
{
$birthday = $this->birthday;
$age = date_diff(date_create($birthday),date_create('today'))->y;
return $age;
}
I render this in Twig like this
<td>{{ entity.getAge() }}</td>
But it shows the following error:
"An exception has been thrown during the rendering of a template ("Warning: date_create() expects parameter 1 to be string, object given") in DuBundle:Voters:index.html.twig at line 32."..
How to correct this problem? I use this in my older projects in Symfony 1.4 with Php templates and it render the current age of the voter without a problem.Why it doesn't work on Twig?
In older Symfony 1.4 I use this way
<td><?php echo date_diff(date_create($total->birthday), date_create('today'))->y; ?></td>
If your $birthday field is a DateTime object, you can use this approach:
public function getAge()
{
if (!$this->birthday) return "";// put here what you want if no birthdayprovided
$now = new \DateTime('now');
return $now->diff($this->birthday)->format("%y");
}
Hope this help
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With