Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig exception on PHP date_create()

Tags:

php

twig

symfony

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>
like image 724
Danielle Rose Mabunga Avatar asked Aug 01 '26 07:08

Danielle Rose Mabunga


1 Answers

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

like image 150
Matteo Avatar answered Aug 03 '26 23:08

Matteo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!