Twig exception in PHP date_create ()

I want to calculate the age base of voters on her birthday, in my essence 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 do it in Twig like this

<td>{{ entity.getAge() }}</td>

      

But it shows the following error:

"An exception was thrown during template rendering (" Warning: date_create () expects parameter 1 to be a string, object is specified ") in DuBundle: Voters: index.html.twig on line 32." ..

How do I fix this problem? I use this in my old projects in Symfony 1.4 with Php templates and it makes the current voter age no problem. Why doesn't it work for Twig?

In old Symfony 1.4 version I use this way

<td><?php echo date_diff(date_create($total->birthday), date_create('today'))->y; ?></td>

      

+3


source to share


1 answer


If your field $birthday

is an object DateTime

, 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 for this help

+4


source







All Articles